From 3fc159f10b5eefe234c9c70ab563e3e2dfe0e0c8 Mon Sep 17 00:00:00 2001 From: Austin Chen Date: Mon, 9 May 2022 12:06:16 -0400 Subject: [PATCH 1/3] Revert "Convert common imports in functions to be absolute" This reverts commit c03518e9063848f4116e61d3a4f1188f7acedbb8. --- functions/src/add-liquidity.ts | 8 +++---- functions/src/change-user-info.ts | 12 +++++----- functions/src/create-answer.ts | 15 ++++++++---- functions/src/create-contract.ts | 12 +++++----- functions/src/create-fold.ts | 8 +++---- functions/src/create-user.ts | 11 +++++---- functions/src/emails.ts | 18 +++++++-------- functions/src/market-close-emails.ts | 2 +- functions/src/on-create-bet.ts | 2 +- functions/src/on-create-comment.ts | 6 ++--- functions/src/on-view.ts | 2 +- functions/src/place-bet.ts | 12 +++++----- functions/src/redeem-shares.ts | 10 ++++---- functions/src/resolve-market.ts | 12 +++++----- functions/src/scripts/cache-views.ts | 6 ++--- .../src/scripts/correct-bet-probability.ts | 6 ++--- functions/src/scripts/create-private-users.ts | 2 +- functions/src/scripts/get-json-dump.ts | 6 ++--- functions/src/scripts/lowercase-fold-tags.ts | 2 +- .../src/scripts/make-contracts-public.ts | 2 +- functions/src/scripts/migrate-contract.ts | 4 ++-- functions/src/scripts/migrate-to-cfmm.ts | 23 +++++++++++++------ functions/src/scripts/migrate-to-dpm-2.ts | 13 +++++++---- .../src/scripts/pay-out-contract-again.ts | 8 +++---- .../scripts/recalculate-contract-totals.ts | 4 ++-- functions/src/scripts/remove-answer-ante.ts | 4 ++-- .../src/scripts/rename-user-contracts.ts | 2 +- functions/src/scripts/update-contract-tags.ts | 4 ++-- functions/src/scripts/update-feed.ts | 6 ++--- .../src/scripts/update-last-comment-time.ts | 4 ++-- functions/src/sell-bet.ts | 12 +++++----- functions/src/sell-shares.ts | 10 ++++---- functions/src/transact.ts | 6 ++--- functions/src/unsubscribe.ts | 2 +- functions/src/update-contract-metrics.ts | 6 ++--- functions/src/update-feed.ts | 16 ++++++------- functions/src/update-recommendations.ts | 12 +++++----- functions/src/update-user-metrics.ts | 10 ++++---- functions/src/utils.ts | 4 ++-- 39 files changed, 162 insertions(+), 142 deletions(-) diff --git a/functions/src/add-liquidity.ts b/functions/src/add-liquidity.ts index 2f6d2446..e37804d3 100644 --- a/functions/src/add-liquidity.ts +++ b/functions/src/add-liquidity.ts @@ -1,11 +1,11 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' -import { Contract } from 'common/contract' -import { User } from 'common/user' -import { removeUndefinedProps } from 'common/util/object' +import { Contract } from '../../common/contract' +import { User } from '../../common/user' +import { removeUndefinedProps } from '../../common/util/object' import { redeemShares } from './redeem-shares' -import { getNewLiquidityProvision } from 'common/add-liquidity' +import { getNewLiquidityProvision } from '../../common/add-liquidity' export const addLiquidity = functions.runWith({ minInstances: 1 }).https.onCall( async ( diff --git a/functions/src/change-user-info.ts b/functions/src/change-user-info.ts index f85d45b3..ab15eb70 100644 --- a/functions/src/change-user-info.ts +++ b/functions/src/change-user-info.ts @@ -2,12 +2,12 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' import { getUser } from './utils' -import { Contract } from 'common/contract' -import { Comment } from 'common/comment' -import { User } from 'common/user' -import { cleanUsername } from 'common/util/clean-username' -import { removeUndefinedProps } from 'common/util/object' -import { Answer } from 'common/answer' +import { Contract } from '../../common/contract' +import { Comment } from '../../common/comment' +import { User } from '../../common/user' +import { cleanUsername } from '../../common/util/clean-username' +import { removeUndefinedProps } from '../../common/util/object' +import { Answer } from '../../common/answer' export const changeUserInfo = functions .runWith({ minInstances: 1 }) diff --git a/functions/src/create-answer.ts b/functions/src/create-answer.ts index 55211585..1da8f350 100644 --- a/functions/src/create-answer.ts +++ b/functions/src/create-answer.ts @@ -1,13 +1,18 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' -import { Contract, DPM, FreeResponse, FullContract } from 'common/contract' -import { User } from 'common/user' -import { getLoanAmount, getNewMultiBetInfo } from 'common/new-bet' -import { Answer, MAX_ANSWER_LENGTH } from 'common/answer' +import { + Contract, + DPM, + FreeResponse, + FullContract, +} from '../../common/contract' +import { User } from '../../common/user' +import { getLoanAmount, getNewMultiBetInfo } from '../../common/new-bet' +import { Answer, MAX_ANSWER_LENGTH } from '../../common/answer' import { getContract, getValues } from './utils' import { sendNewAnswerEmail } from './emails' -import { Bet } from 'common/bet' +import { Bet } from '../../common/bet' export const createAnswer = functions.runWith({ minInstances: 1 }).https.onCall( async ( diff --git a/functions/src/create-contract.ts b/functions/src/create-contract.ts index 5345469e..dfc8128d 100644 --- a/functions/src/create-contract.ts +++ b/functions/src/create-contract.ts @@ -13,10 +13,10 @@ import { MAX_QUESTION_LENGTH, MAX_TAG_LENGTH, outcomeType, -} from 'common/contract' -import { slugify } from 'common/util/slugify' -import { randomString } from 'common/util/random' -import { getNewContract } from 'common/new-contract' +} from '../../common/contract' +import { slugify } from '../../common/util/slugify' +import { randomString } from '../../common/util/random' +import { getNewContract } from '../../common/new-contract' import { FIXED_ANTE, getAnteBets, @@ -24,8 +24,8 @@ import { getFreeAnswerAnte, HOUSE_LIQUIDITY_PROVIDER_ID, MINIMUM_ANTE, -} from 'common/antes' -import { getNoneAnswer } from 'common/answer' +} from '../../common/antes' +import { getNoneAnswer } from '../../common/answer' export const createContract = functions .runWith({ minInstances: 1 }) diff --git a/functions/src/create-fold.ts b/functions/src/create-fold.ts index 5cf40b22..36d1d269 100644 --- a/functions/src/create-fold.ts +++ b/functions/src/create-fold.ts @@ -3,10 +3,10 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getUser } from './utils' -import { Contract } from 'common/contract' -import { slugify } from 'common/util/slugify' -import { randomString } from 'common/util/random' -import { Fold } from 'common/fold' +import { Contract } from '../../common/contract' +import { slugify } from '../../common/util/slugify' +import { randomString } from '../../common/util/random' +import { Fold } from '../../common/fold' export const createFold = functions.runWith({ minInstances: 1 }).https.onCall( async ( diff --git a/functions/src/create-user.ts b/functions/src/create-user.ts index dd2b5275..f73b868b 100644 --- a/functions/src/create-user.ts +++ b/functions/src/create-user.ts @@ -6,12 +6,15 @@ import { STARTING_BALANCE, SUS_STARTING_BALANCE, User, -} from 'common/user' +} from '../../common/user' import { getUser, getUserByUsername } from './utils' -import { randomString } from 'common/util/random' -import { cleanDisplayName, cleanUsername } from 'common/util/clean-username' +import { randomString } from '../../common/util/random' +import { + cleanDisplayName, + cleanUsername, +} from '../../common/util/clean-username' import { sendWelcomeEmail } from './emails' -import { isWhitelisted } from 'common/envs/constants' +import { isWhitelisted } from '../../common/envs/constants' export const createUser = functions .runWith({ minInstances: 1 }) diff --git a/functions/src/emails.ts b/functions/src/emails.ts index 4c434bcf..c3b70734 100644 --- a/functions/src/emails.ts +++ b/functions/src/emails.ts @@ -1,14 +1,14 @@ import * as _ from 'lodash' -import { DOMAIN, PROJECT_ID } from 'common/envs/constants' -import { Answer } from 'common/answer' -import { Bet } from 'common/bet' -import { getProbability } from 'common/calculate' -import { Comment } from 'common/comment' -import { Contract, FreeResponseContract } from 'common/contract' -import { CREATOR_FEE } from 'common/fees' -import { PrivateUser, User } from 'common/user' -import { formatMoney, formatPercent } from 'common/util/format' +import { DOMAIN, PROJECT_ID } from '../../common/envs/constants' +import { Answer } from '../../common/answer' +import { Bet } from '../../common/bet' +import { getProbability } from '../../common/calculate' +import { Comment } from '../../common/comment' +import { Contract, FreeResponseContract } from '../../common/contract' +import { CREATOR_FEE } from '../../common/fees' +import { PrivateUser, User } from '../../common/user' +import { formatMoney, formatPercent } from '../../common/util/format' import { sendTemplateEmail, sendTextEmail } from './send-email' import { getPrivateUser, getUser } from './utils' diff --git a/functions/src/market-close-emails.ts b/functions/src/market-close-emails.ts index 3adc5b6d..bb144600 100644 --- a/functions/src/market-close-emails.ts +++ b/functions/src/market-close-emails.ts @@ -1,7 +1,7 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' -import { Contract } from 'common/contract' +import { Contract } from '../../common/contract' import { getPrivateUser, getUserByUsername } from './utils' import { sendMarketCloseEmail } from './emails' diff --git a/functions/src/on-create-bet.ts b/functions/src/on-create-bet.ts index e3cf0ece..deaa4c4a 100644 --- a/functions/src/on-create-bet.ts +++ b/functions/src/on-create-bet.ts @@ -3,7 +3,7 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getContract } from './utils' -import { Bet } from 'common/bet' +import { Bet } from '../../common/bet' const firestore = admin.firestore() diff --git a/functions/src/on-create-comment.ts b/functions/src/on-create-comment.ts index 654f9055..18fc6757 100644 --- a/functions/src/on-create-comment.ts +++ b/functions/src/on-create-comment.ts @@ -3,10 +3,10 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getContract, getUser, getValues } from './utils' -import { Comment } from 'common/comment' +import { Comment } from '../../common/comment' import { sendNewCommentEmail } from './emails' -import { Bet } from 'common/bet' -import { Answer } from 'common/answer' +import { Bet } from '../../common/bet' +import { Answer } from '../../common/answer' const firestore = admin.firestore() diff --git a/functions/src/on-view.ts b/functions/src/on-view.ts index 6e08ae76..d2f746d5 100644 --- a/functions/src/on-view.ts +++ b/functions/src/on-view.ts @@ -1,6 +1,6 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' -import { View } from 'common/tracking' +import { View } from '../../common/tracking' const firestore = admin.firestore() diff --git a/functions/src/place-bet.ts b/functions/src/place-bet.ts index 083c8bc2..74487126 100644 --- a/functions/src/place-bet.ts +++ b/functions/src/place-bet.ts @@ -1,18 +1,18 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' -import { Contract } from 'common/contract' -import { User } from 'common/user' +import { Contract } from '../../common/contract' +import { User } from '../../common/user' import { getNewBinaryCpmmBetInfo, getNewBinaryDpmBetInfo, getNewMultiBetInfo, getLoanAmount, -} from 'common/new-bet' -import { addObjects, removeUndefinedProps } from 'common/util/object' -import { Bet } from 'common/bet' +} from '../../common/new-bet' +import { addObjects, removeUndefinedProps } from '../../common/util/object' +import { Bet } from '../../common/bet' import { redeemShares } from './redeem-shares' -import { Fees } from 'common/fees' +import { Fees } from '../../common/fees' export const placeBet = functions.runWith({ minInstances: 1 }).https.onCall( async ( diff --git a/functions/src/redeem-shares.ts b/functions/src/redeem-shares.ts index a43aa509..08d87a8b 100644 --- a/functions/src/redeem-shares.ts +++ b/functions/src/redeem-shares.ts @@ -1,12 +1,12 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' -import { Bet } from 'common/bet' -import { getProbability } from 'common/calculate' +import { Bet } from '../../common/bet' +import { getProbability } from '../../common/calculate' -import { Binary, CPMM, FullContract } from 'common/contract' -import { noFees } from 'common/fees' -import { User } from 'common/user' +import { Binary, CPMM, FullContract } from '../../common/contract' +import { noFees } from '../../common/fees' +import { User } from '../../common/user' export const redeemShares = async (userId: string, contractId: string) => { return await firestore.runTransaction(async (transaction) => { diff --git a/functions/src/resolve-market.ts b/functions/src/resolve-market.ts index 5ee82ff5..5a2edec2 100644 --- a/functions/src/resolve-market.ts +++ b/functions/src/resolve-market.ts @@ -2,14 +2,14 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' import * as _ from 'lodash' -import { Contract } from 'common/contract' -import { User } from 'common/user' -import { Bet } from 'common/bet' +import { Contract } from '../../common/contract' +import { User } from '../../common/user' +import { Bet } from '../../common/bet' import { getUser, isProd, payUser } from './utils' import { sendMarketResolutionEmail } from './emails' -import { getLoanPayouts, getPayouts } from 'common/payouts' -import { removeUndefinedProps } from 'common/util/object' -import { LiquidityProvision } from 'common/liquidity-provision' +import { getLoanPayouts, getPayouts } from '../../common/payouts' +import { removeUndefinedProps } from '../../common/util/object' +import { LiquidityProvision } from '../../common/liquidity-provision' export const resolveMarket = functions .runWith({ minInstances: 1 }) diff --git a/functions/src/scripts/cache-views.ts b/functions/src/scripts/cache-views.ts index c7ed661f..c7145a1e 100644 --- a/functions/src/scripts/cache-views.ts +++ b/functions/src/scripts/cache-views.ts @@ -5,9 +5,9 @@ import { initAdmin } from './script-init' initAdmin() import { getValues } from '../utils' -import { View } from 'common/tracking' -import { User } from 'common/user' -import { batchedWaitAll } from 'common/util/promise' +import { View } from '../../../common/tracking' +import { User } from '../../../common/user' +import { batchedWaitAll } from '../../../common/util/promise' const firestore = admin.firestore() diff --git a/functions/src/scripts/correct-bet-probability.ts b/functions/src/scripts/correct-bet-probability.ts index e65b4ddf..3b57dbeb 100644 --- a/functions/src/scripts/correct-bet-probability.ts +++ b/functions/src/scripts/correct-bet-probability.ts @@ -4,9 +4,9 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Bet } from 'common/bet' -import { getDpmProbability } from 'common/calculate-dpm' -import { Binary, Contract, DPM, FullContract } from 'common/contract' +import { Bet } from '../../../common/bet' +import { getDpmProbability } from '../../../common/calculate-dpm' +import { Binary, Contract, DPM, FullContract } from '../../../common/contract' type DocRef = admin.firestore.DocumentReference const firestore = admin.firestore() diff --git a/functions/src/scripts/create-private-users.ts b/functions/src/scripts/create-private-users.ts index a83bb53e..8051a447 100644 --- a/functions/src/scripts/create-private-users.ts +++ b/functions/src/scripts/create-private-users.ts @@ -4,7 +4,7 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { PrivateUser, STARTING_BALANCE, User } from 'common/user' +import { PrivateUser, STARTING_BALANCE, User } from '../../../common/user' const firestore = admin.firestore() diff --git a/functions/src/scripts/get-json-dump.ts b/functions/src/scripts/get-json-dump.ts index 3027ce45..b9909132 100644 --- a/functions/src/scripts/get-json-dump.ts +++ b/functions/src/scripts/get-json-dump.ts @@ -5,10 +5,10 @@ import * as fs from 'fs' import { initAdmin } from './script-init' initAdmin() -import { Bet } from 'common/bet' -import { Contract } from 'common/contract' +import { Bet } from '../../../common/bet' +import { Contract } from '../../../common/contract' import { getValues } from '../utils' -import { Comment } from 'common/comment' +import { Comment } from '../../../common/comment' const firestore = admin.firestore() diff --git a/functions/src/scripts/lowercase-fold-tags.ts b/functions/src/scripts/lowercase-fold-tags.ts index f5d01bfe..80b79a33 100644 --- a/functions/src/scripts/lowercase-fold-tags.ts +++ b/functions/src/scripts/lowercase-fold-tags.ts @@ -5,7 +5,7 @@ import { initAdmin } from './script-init' initAdmin() import { getValues } from '../utils' -import { Fold } from 'common/fold' +import { Fold } from '../../../common/fold' async function lowercaseFoldTags() { const firestore = admin.firestore() diff --git a/functions/src/scripts/make-contracts-public.ts b/functions/src/scripts/make-contracts-public.ts index 5d958f13..19d2e196 100644 --- a/functions/src/scripts/make-contracts-public.ts +++ b/functions/src/scripts/make-contracts-public.ts @@ -4,7 +4,7 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Contract } from 'common/contract' +import { Contract } from '../../../common/contract' const firestore = admin.firestore() diff --git a/functions/src/scripts/migrate-contract.ts b/functions/src/scripts/migrate-contract.ts index 7127f371..718cf62e 100644 --- a/functions/src/scripts/migrate-contract.ts +++ b/functions/src/scripts/migrate-contract.ts @@ -4,8 +4,8 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Bet } from 'common/bet' -import { Contract } from 'common/contract' +import { Bet } from '../../../common/bet' +import { Contract } from '../../../common/contract' type DocRef = admin.firestore.DocumentReference diff --git a/functions/src/scripts/migrate-to-cfmm.ts b/functions/src/scripts/migrate-to-cfmm.ts index 9dd8c63e..874011ca 100644 --- a/functions/src/scripts/migrate-to-cfmm.ts +++ b/functions/src/scripts/migrate-to-cfmm.ts @@ -4,13 +4,22 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Binary, Contract, CPMM, DPM, FullContract } from 'common/contract' -import { Bet } from 'common/bet' -import { calculateDpmPayout, getDpmProbability } from 'common/calculate-dpm' -import { User } from 'common/user' -import { getCpmmInitialLiquidity } from 'common/antes' -import { noFees } from 'common/fees' -import { addObjects } from 'common/util/object' +import { + Binary, + Contract, + CPMM, + DPM, + FullContract, +} from '../../../common/contract' +import { Bet } from '../../../common/bet' +import { + calculateDpmPayout, + getDpmProbability, +} from '../../../common/calculate-dpm' +import { User } from '../../../common/user' +import { getCpmmInitialLiquidity } from '../../../common/antes' +import { noFees } from '../../../common/fees' +import { addObjects } from '../../../common/util/object' type DocRef = admin.firestore.DocumentReference diff --git a/functions/src/scripts/migrate-to-dpm-2.ts b/functions/src/scripts/migrate-to-dpm-2.ts index 81e99d98..2c6f066f 100644 --- a/functions/src/scripts/migrate-to-dpm-2.ts +++ b/functions/src/scripts/migrate-to-dpm-2.ts @@ -4,11 +4,14 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Binary, Contract, DPM, FullContract } from 'common/contract' -import { Bet } from 'common/bet' -import { calculateDpmShares, getDpmProbability } from 'common/calculate-dpm' -import { getSellBetInfo } from 'common/sell-bet' -import { User } from 'common/user' +import { Binary, Contract, DPM, FullContract } from '../../../common/contract' +import { Bet } from '../../../common/bet' +import { + calculateDpmShares, + getDpmProbability, +} from '../../../common/calculate-dpm' +import { getSellBetInfo } from '../../../common/sell-bet' +import { User } from '../../../common/user' type DocRef = admin.firestore.DocumentReference diff --git a/functions/src/scripts/pay-out-contract-again.ts b/functions/src/scripts/pay-out-contract-again.ts index 0e56429f..7672bf7b 100644 --- a/functions/src/scripts/pay-out-contract-again.ts +++ b/functions/src/scripts/pay-out-contract-again.ts @@ -4,10 +4,10 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Bet } from 'common/bet' -import { Contract } from 'common/contract' -import { getLoanPayouts, getPayouts } from 'common/payouts' -import { filterDefined } from 'common/util/array' +import { Bet } from '../../../common/bet' +import { Contract } from '../../../common/contract' +import { getLoanPayouts, getPayouts } from '../../../common/payouts' +import { filterDefined } from '../../../common/util/array' type DocRef = admin.firestore.DocumentReference diff --git a/functions/src/scripts/recalculate-contract-totals.ts b/functions/src/scripts/recalculate-contract-totals.ts index 91165781..39942542 100644 --- a/functions/src/scripts/recalculate-contract-totals.ts +++ b/functions/src/scripts/recalculate-contract-totals.ts @@ -4,8 +4,8 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Bet } from 'common/bet' -import { Contract } from 'common/contract' +import { Bet } from '../../../common/bet' +import { Contract } from '../../../common/contract' type DocRef = admin.firestore.DocumentReference diff --git a/functions/src/scripts/remove-answer-ante.ts b/functions/src/scripts/remove-answer-ante.ts index 8b026174..eb49af6c 100644 --- a/functions/src/scripts/remove-answer-ante.ts +++ b/functions/src/scripts/remove-answer-ante.ts @@ -4,8 +4,8 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Bet } from 'common/bet' -import { Contract } from 'common/contract' +import { Bet } from '../../../common/bet' +import { Contract } from '../../../common/contract' import { getValues } from '../utils' async function removeAnswerAnte() { diff --git a/functions/src/scripts/rename-user-contracts.ts b/functions/src/scripts/rename-user-contracts.ts index bcb4fea6..9b0f569b 100644 --- a/functions/src/scripts/rename-user-contracts.ts +++ b/functions/src/scripts/rename-user-contracts.ts @@ -4,7 +4,7 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Contract } from 'common/contract' +import { Contract } from '../../../common/contract' import { getValues } from '../utils' const firestore = admin.firestore() diff --git a/functions/src/scripts/update-contract-tags.ts b/functions/src/scripts/update-contract-tags.ts index 7e671c9f..1dda5615 100644 --- a/functions/src/scripts/update-contract-tags.ts +++ b/functions/src/scripts/update-contract-tags.ts @@ -4,8 +4,8 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Contract } from 'common/contract' -import { parseTags } from 'common/util/parse' +import { Contract } from '../../../common/contract' +import { parseTags } from '../../../common/util/parse' import { getValues } from '../utils' async function updateContractTags() { diff --git a/functions/src/scripts/update-feed.ts b/functions/src/scripts/update-feed.ts index f98631dd..25a0b14f 100644 --- a/functions/src/scripts/update-feed.ts +++ b/functions/src/scripts/update-feed.ts @@ -5,9 +5,9 @@ import { initAdmin } from './script-init' initAdmin() import { getValues } from '../utils' -import { User } from 'common/user' -import { batchedWaitAll } from 'common/util/promise' -import { Contract } from 'common/contract' +import { User } from '../../../common/user' +import { batchedWaitAll } from '../../../common/util/promise' +import { Contract } from '../../../common/contract' import { updateWordScores } from '../update-recommendations' import { getFeedContracts, doUserFeedUpdate } from '../update-feed' diff --git a/functions/src/scripts/update-last-comment-time.ts b/functions/src/scripts/update-last-comment-time.ts index 99d7f52d..ae950fbe 100644 --- a/functions/src/scripts/update-last-comment-time.ts +++ b/functions/src/scripts/update-last-comment-time.ts @@ -4,9 +4,9 @@ import * as _ from 'lodash' import { initAdmin } from './script-init' initAdmin() -import { Contract } from 'common/contract' +import { Contract } from '../../../common/contract' import { getValues } from '../utils' -import { Comment } from 'common/comment' +import { Comment } from '../../../common/comment' async function updateLastCommentTime() { const firestore = admin.firestore() diff --git a/functions/src/sell-bet.ts b/functions/src/sell-bet.ts index c685498b..fff88716 100644 --- a/functions/src/sell-bet.ts +++ b/functions/src/sell-bet.ts @@ -1,12 +1,12 @@ import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' -import { Contract } from 'common/contract' -import { User } from 'common/user' -import { Bet } from 'common/bet' -import { getSellBetInfo } from 'common/sell-bet' -import { addObjects, removeUndefinedProps } from 'common/util/object' -import { Fees } from 'common/fees' +import { Contract } from '../../common/contract' +import { User } from '../../common/user' +import { Bet } from '../../common/bet' +import { getSellBetInfo } from '../../common/sell-bet' +import { addObjects, removeUndefinedProps } from '../../common/util/object' +import { Fees } from '../../common/fees' export const sellBet = functions.runWith({ minInstances: 1 }).https.onCall( async ( diff --git a/functions/src/sell-shares.ts b/functions/src/sell-shares.ts index 158a5f6a..e4dbcbc9 100644 --- a/functions/src/sell-shares.ts +++ b/functions/src/sell-shares.ts @@ -2,12 +2,12 @@ import * as _ from 'lodash' import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' -import { Binary, CPMM, FullContract } from 'common/contract' -import { User } from 'common/user' -import { getCpmmSellBetInfo } from 'common/sell-bet' -import { addObjects, removeUndefinedProps } from 'common/util/object' +import { Binary, CPMM, FullContract } from '../../common/contract' +import { User } from '../../common/user' +import { getCpmmSellBetInfo } from '../../common/sell-bet' +import { addObjects, removeUndefinedProps } from '../../common/util/object' import { getValues } from './utils' -import { Bet } from 'common/bet' +import { Bet } from '../../common/bet' export const sellShares = functions.runWith({ minInstances: 1 }).https.onCall( async ( diff --git a/functions/src/transact.ts b/functions/src/transact.ts index 77323638..79b5ccb8 100644 --- a/functions/src/transact.ts +++ b/functions/src/transact.ts @@ -1,9 +1,9 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' -import { User } from 'common/user' -import { Txn } from 'common/txn' -import { removeUndefinedProps } from 'common/util/object' +import { User } from '../../common/user' +import { Txn } from '../../common/txn' +import { removeUndefinedProps } from '../../common/util/object' export const transact = functions .runWith({ minInstances: 1 }) diff --git a/functions/src/unsubscribe.ts b/functions/src/unsubscribe.ts index 7c9442d7..c6edee92 100644 --- a/functions/src/unsubscribe.ts +++ b/functions/src/unsubscribe.ts @@ -2,7 +2,7 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getUser } from './utils' -import { PrivateUser } from 'common/user' +import { PrivateUser } from '../../common/user' export const unsubscribe = functions .runWith({ minInstances: 1 }) diff --git a/functions/src/update-contract-metrics.ts b/functions/src/update-contract-metrics.ts index 9214d2dc..c3801df6 100644 --- a/functions/src/update-contract-metrics.ts +++ b/functions/src/update-contract-metrics.ts @@ -3,9 +3,9 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getValues } from './utils' -import { Contract } from 'common/contract' -import { Bet } from 'common/bet' -import { batchedWaitAll } from 'common/util/promise' +import { Contract } from '../../common/contract' +import { Bet } from '../../common/bet' +import { batchedWaitAll } from '../../common/util/promise' const firestore = admin.firestore() diff --git a/functions/src/update-feed.ts b/functions/src/update-feed.ts index 3bfa7949..accd48e8 100644 --- a/functions/src/update-feed.ts +++ b/functions/src/update-feed.ts @@ -3,21 +3,21 @@ import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' import { getValue, getValues } from './utils' -import { Contract } from 'common/contract' -import { logInterpolation } from 'common/util/math' -import { DAY_MS } from 'common/util/time' +import { Contract } from '../../common/contract' +import { logInterpolation } from '../../common/util/math' +import { DAY_MS } from '../../common/util/time' import { getProbability, getOutcomeProbability, getTopAnswer, -} from 'common/calculate' -import { Bet } from 'common/bet' -import { Comment } from 'common/comment' -import { User } from 'common/user' +} from '../../common/calculate' +import { Bet } from '../../common/bet' +import { Comment } from '../../common/comment' +import { User } from '../../common/user' import { getContractScore, MAX_FEED_CONTRACTS, -} from 'common/recommended-contracts' +} from '../../common/recommended-contracts' import { callCloudFunction } from './call-cloud-function' const firestore = admin.firestore() diff --git a/functions/src/update-recommendations.ts b/functions/src/update-recommendations.ts index e18e7c0e..4e656dda 100644 --- a/functions/src/update-recommendations.ts +++ b/functions/src/update-recommendations.ts @@ -3,12 +3,12 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getValue, getValues } from './utils' -import { Contract } from 'common/contract' -import { Bet } from 'common/bet' -import { User } from 'common/user' -import { ClickEvent } from 'common/tracking' -import { getWordScores } from 'common/recommended-contracts' -import { batchedWaitAll } from 'common/util/promise' +import { Contract } from '../../common/contract' +import { Bet } from '../../common/bet' +import { User } from '../../common/user' +import { ClickEvent } from '../../common/tracking' +import { getWordScores } from '../../common/recommended-contracts' +import { batchedWaitAll } from '../../common/util/promise' import { callCloudFunction } from './call-cloud-function' const firestore = admin.firestore() diff --git a/functions/src/update-user-metrics.ts b/functions/src/update-user-metrics.ts index 6f755622..70fd1bc5 100644 --- a/functions/src/update-user-metrics.ts +++ b/functions/src/update-user-metrics.ts @@ -3,11 +3,11 @@ import * as admin from 'firebase-admin' import * as _ from 'lodash' import { getValues } from './utils' -import { Contract } from 'common/contract' -import { Bet } from 'common/bet' -import { User } from 'common/user' -import { batchedWaitAll } from 'common/util/promise' -import { calculatePayout } from 'common/calculate' +import { Contract } from '../../common/contract' +import { Bet } from '../../common/bet' +import { User } from '../../common/user' +import { batchedWaitAll } from '../../common/util/promise' +import { calculatePayout } from '../../common/calculate' const firestore = admin.firestore() diff --git a/functions/src/utils.ts b/functions/src/utils.ts index d0ab8c5d..28ef5445 100644 --- a/functions/src/utils.ts +++ b/functions/src/utils.ts @@ -1,7 +1,7 @@ import * as admin from 'firebase-admin' -import { Contract } from 'common/contract' -import { PrivateUser, User } from 'common/user' +import { Contract } from '../../common/contract' +import { PrivateUser, User } from '../../common/user' export const isProd = admin.instanceId().app.options.projectId === 'mantic-markets' From e8ab86355746ccd29ac3bf191a15781c2fb20c6e Mon Sep 17 00:00:00 2001 From: James Grugett Date: Mon, 9 May 2022 12:38:33 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=94=8D=20Algolia=20search=20=20(#136)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add algolia and instantsearch packages * Switch to hooks-web package * Implement algolia search! * Fix types * Fix tags page * Closed sort option * Implement select for filtering on open, closed, resolved, all. * Support search in dev environment * Fix runtime error in landing page --- common/envs/constants.ts | 2 +- common/util/format.ts | 4 +- web/components/contract-search.tsx | 221 ++++++++++++++ web/components/contract/contracts-list.tsx | 326 ++------------------- web/components/feed-create.tsx | 7 +- web/components/user-page.tsx | 2 +- web/hooks/use-sort-and-query-params.tsx | 83 ++++-- web/package.json | 6 +- web/pages/_document.tsx | 7 + web/pages/fold/[...slugs]/index.tsx | 22 +- web/pages/landing-page.tsx | 8 +- web/pages/markets.tsx | 40 +-- web/pages/tag/[tag].tsx | 29 +- yarn.lock | 242 ++++++++++++++- 14 files changed, 579 insertions(+), 420 deletions(-) create mode 100644 web/components/contract-search.tsx diff --git a/common/envs/constants.ts b/common/envs/constants.ts index b87948a7..dc753021 100644 --- a/common/envs/constants.ts +++ b/common/envs/constants.ts @@ -2,7 +2,7 @@ import { DEV_CONFIG } from './dev' import { EnvConfig, PROD_CONFIG } from './prod' import { THEOREMONE_CONFIG } from './theoremone' -const ENV = process.env.NEXT_PUBLIC_FIREBASE_ENV ?? 'PROD' +export const ENV = process.env.NEXT_PUBLIC_FIREBASE_ENV ?? 'PROD' const CONFIGS = { PROD: PROD_CONFIG, diff --git a/common/util/format.ts b/common/util/format.ts index 765c34d9..3310d902 100644 --- a/common/util/format.ts +++ b/common/util/format.ts @@ -9,9 +9,7 @@ const formatter = new Intl.NumberFormat('en-US', { export function formatMoney(amount: number) { const newAmount = Math.round(amount) === 0 ? 0 : Math.floor(amount) // handle -0 case - return ( - ENV_CONFIG.moneyMoniker + formatter.format(newAmount).replace('$', '') - ) + return ENV_CONFIG.moneyMoniker + formatter.format(newAmount).replace('$', '') } export function formatWithCommas(amount: number) { diff --git a/web/components/contract-search.tsx b/web/components/contract-search.tsx new file mode 100644 index 00000000..b46bee6e --- /dev/null +++ b/web/components/contract-search.tsx @@ -0,0 +1,221 @@ +import algoliasearch from 'algoliasearch/lite' +import { + InstantSearch, + SearchBox, + SortBy, + useInfiniteHits, + useRange, + useRefinementList, + useSortBy, + useToggleRefinement, +} from 'react-instantsearch-hooks-web' +import { Contract } from '../../common/contract' +import { + Sort, + useInitialQueryAndSort, + useUpdateQueryAndSort, +} from '../hooks/use-sort-and-query-params' +import { ContractsGrid } from './contract/contracts-list' +import { Row } from './layout/row' +import { useEffect, useState } from 'react' +import { Spacer } from './layout/spacer' +import { useRouter } from 'next/router' +import { ENV } from 'common/envs/constants' + +const searchClient = algoliasearch( + 'GJQPAYENIF', + '75c28fc084a80e1129d427d470cf41a3' +) + +const indexPrefix = ENV === 'DEV' ? 'dev-' : '' +console.log('env', ENV, indexPrefix) + +const sortIndexes = [ + { label: 'Newest', value: indexPrefix + 'contracts-newest' }, + { label: 'Oldest', value: indexPrefix + 'contracts-oldest' }, + { label: 'Most traded', value: indexPrefix + 'contracts-most-traded' }, + { label: '24h volume', value: indexPrefix + 'contracts-24-hour-vol' }, + { label: 'Close date', value: indexPrefix + 'contracts-close-date' }, + { label: 'Resolve date', value: indexPrefix + 'contracts-resolve-date' }, +] + +type filter = 'open' | 'closed' | 'resolved' | 'all' + +export function ContractSearch(props: { + querySortOptions?: { + defaultSort: Sort + filter?: { + creatorId?: string + tag?: string + } + shouldLoadFromStorage?: boolean + } +}) { + const { querySortOptions } = props + + const { initialSort } = useInitialQueryAndSort(querySortOptions) + + const sort = sortIndexes + .map(({ value }) => value) + .includes(`${indexPrefix}contracts-${initialSort ?? ''}`) + ? initialSort + : querySortOptions?.defaultSort + + const [filter, setFilter] = useState('open') + + if (!sort) return <> + return ( + + + + + + + + + + + ) +} + +export function ContractSearchInner(props: { + querySortOptions?: { + defaultSort: Sort + filter?: { + creatorId?: string + tag?: string + } + shouldLoadFromStorage?: boolean + } + filter: filter +}) { + const { querySortOptions, filter } = props + const { initialQuery } = useInitialQueryAndSort(querySortOptions) + + const { query, setQuery, setSort } = useUpdateQueryAndSort({ + shouldLoadFromStorage: true, + }) + + useEffect(() => { + console.log('initial query', initialQuery) + setQuery(initialQuery) + }, [initialQuery]) + + const { currentRefinement: index } = useSortBy({ + items: [], + }) + + useEffect(() => { + console.log('setting query', query) + setQuery(query) + }, [query]) + + useEffect(() => { + console.log('effect sort', 'curr', index) + const sort = index.split('contracts-')[1] as Sort + if (sort) { + setSort(sort) + } + }, [index]) + + const creatorId = querySortOptions?.filter?.creatorId + useFilterCreator(creatorId) + + const tag = querySortOptions?.filter?.tag + useFilterTag(tag) + + useFilterClosed( + filter === 'closed' + ? true + : filter === 'all' || filter === 'resolved' + ? undefined + : false + ) + useFilterResolved( + filter === 'resolved' ? true : filter === 'all' ? undefined : false + ) + + const { showMore, hits, isLastPage } = useInfiniteHits() + const contracts = hits as any as Contract[] + + const router = useRouter() + const hasLoaded = contracts.length > 0 || router.isReady + + return ( +
+ + + {hasLoaded && ( + + )} +
+ ) +} + +const useFilterCreator = (creatorId: string | undefined) => { + const { refine } = useRefinementList({ attribute: 'creatorId' }) + useEffect(() => { + if (creatorId) refine(creatorId) + }, [creatorId, refine]) +} + +const useFilterTag = (tag: string | undefined) => { + const { refine } = useRefinementList({ attribute: 'lowercaseTags' }) + useEffect(() => { + if (tag) refine(tag.toLowerCase()) + }, [tag, refine]) +} + +const useFilterClosed = (value: boolean | undefined) => { + const [now] = useState(Date.now()) + useRange({ + attribute: 'closeTime', + min: value === false ? now : undefined, + max: value ? now : undefined, + }) +} + +const useFilterResolved = (value: boolean | undefined) => { + // Note (James): I don't know why this works. + const { refine: refineResolved } = useToggleRefinement({ + attribute: value === undefined ? 'non-existant-field' : 'isResolved', + on: true, + off: value === undefined ? undefined : false, + }) + useEffect(() => { + refineResolved({ isRefined: !value }) + }, [value]) +} diff --git a/web/components/contract/contracts-list.tsx b/web/components/contract/contracts-list.tsx index 76cc8752..705de807 100644 --- a/web/components/contract/contracts-list.tsx +++ b/web/components/contract/contracts-list.tsx @@ -1,41 +1,19 @@ import _ from 'lodash' -import Link from 'next/link' -import clsx from 'clsx' -import { useEffect, useState } from 'react' -import { - contractMetrics, - Contract, - listContracts, - getBinaryProb, -} from 'web/lib/firebase/contracts' -import { User } from 'web/lib/firebase/users' +import { Contract } from '../../lib/firebase/contracts' +import { User } from '../../lib/firebase/users' import { Col } from '../layout/col' import { SiteLink } from '../site-link' import { ContractCard } from './contract-card' -import { - Sort, - useQueryAndSortParams, -} from 'web/hooks/use-sort-and-query-params' -import { Answer } from 'common/answer' -import { LoadingIndicator } from '../loading-indicator' +import { ContractSearch } from '../contract-search' export function ContractsGrid(props: { contracts: Contract[] - showHotVolume?: boolean + loadMore: () => void + hasMore: boolean showCloseTime?: boolean }) { - const { showCloseTime } = props - const PAGE_SIZE = 100 - const [page, setPage] = useState(1) - - const [resolvedContracts, activeContracts] = _.partition( - props.contracts, - (c) => c.isResolved - ) - const allContracts = [...activeContracts, ...resolvedContracts] - const showMore = allContracts.length > PAGE_SIZE * page - const contracts = allContracts.slice(0, PAGE_SIZE * page) + const { contracts, showCloseTime, hasMore, loadMore } = props if (contracts.length === 0) { return ( @@ -49,306 +27,38 @@ export function ContractsGrid(props: { } return ( - <> +
    {contracts.map((contract) => ( ))}
- {/* Show a link that increases the page num when clicked */} - {showMore && ( + {hasMore && ( )} - - ) -} - -const MAX_GROUPED_CONTRACTS_DISPLAYED = 6 - -function CreatorContractsGrid(props: { contracts: Contract[] }) { - const { contracts } = props - - const byCreator = _.groupBy(contracts, (contract) => contract.creatorId) - const creator7DayVol = _.mapValues(byCreator, (contracts) => - _.sumBy(contracts, (contract) => contract.volume7Days) - ) - const creatorIds = _.sortBy( - Object.keys(byCreator), - (creatorId) => -1 * creator7DayVol[creatorId] - ) - - let numContracts = 0 - let maxIndex = 0 - for (; maxIndex < creatorIds.length; maxIndex++) { - numContracts += Math.min( - MAX_GROUPED_CONTRACTS_DISPLAYED, - byCreator[creatorIds[maxIndex]].length - ) - if (numContracts > MAX_CONTRACTS_DISPLAYED) break - } - - const creatorIdsSubset = creatorIds.slice(0, maxIndex) - - return ( - - {creatorIdsSubset.map((creatorId) => { - const { creatorUsername, creatorName } = byCreator[creatorId][0] - - return ( - - - {creatorName} - - -
    - {byCreator[creatorId] - .slice(0, MAX_GROUPED_CONTRACTS_DISPLAYED) - .map((contract) => ( - - ))} -
- - {byCreator[creatorId].length > MAX_GROUPED_CONTRACTS_DISPLAYED ? ( - - e.stopPropagation()} - > - See all - - - ) : ( -
- )} - - ) - })} ) } -function TagContractsGrid(props: { contracts: Contract[] }) { - const { contracts } = props - - const contractTags = _.flatMap(contracts, (contract) => { - const { tags } = contract - return tags.map((tag) => ({ - tag, - contract, - })) - }) - const groupedByTag = _.groupBy(contractTags, ({ tag }) => tag) - const byTag = _.mapValues(groupedByTag, (contractTags) => - contractTags.map(({ contract }) => contract) - ) - const tag7DayVol = _.mapValues(byTag, (contracts) => - _.sumBy(contracts, (contract) => contract.volume7Days) - ) - const tags = _.sortBy( - Object.keys(byTag), - (creatorId) => -1 * tag7DayVol[creatorId] - ) - - let numContracts = 0 - let maxIndex = 0 - for (; maxIndex < tags.length; maxIndex++) { - numContracts += Math.min( - MAX_GROUPED_CONTRACTS_DISPLAYED, - byTag[tags[maxIndex]].length - ) - if (numContracts > MAX_CONTRACTS_DISPLAYED) break - } - - const tagsSubset = tags.slice(0, maxIndex) +export function CreatorContractsList(props: { creator: User }) { + const { creator } = props return ( - - {tagsSubset.map((tag) => { - return ( - - - #{tag} - - -
    - {byTag[tag] - .slice(0, MAX_GROUPED_CONTRACTS_DISPLAYED) - .map((contract) => ( - - ))} -
- - {byTag[tag].length > MAX_GROUPED_CONTRACTS_DISPLAYED ? ( - - e.stopPropagation()} - > - See all - - - ) : ( -
- )} - - ) - })} - - ) -} - -const MAX_CONTRACTS_DISPLAYED = 99 - -export function SearchableGrid(props: { - contracts: Contract[] | undefined - byOneCreator?: boolean - querySortOptions?: { - defaultSort: Sort - shouldLoadFromStorage?: boolean - } -}) { - const { contracts, byOneCreator, querySortOptions } = props - - const { query, setQuery, sort, setSort } = - useQueryAndSortParams(querySortOptions) - - const queryWords = query.toLowerCase().split(' ') - function check(corpus: String) { - return queryWords.every((word) => corpus.toLowerCase().includes(word)) - } - - let matches = (contracts ?? []).filter( - (c) => - check(c.question) || - check(c.description) || - check(c.creatorName) || - check(c.creatorUsername) || - check(c.lowercaseTags.map((tag) => `#${tag}`).join(' ')) || - check( - ((c as any).answers ?? []) - .map((answer: Answer) => answer.text) - .join(' ') - ) - ) - - if (sort === 'newest' || sort === 'all') { - matches.sort((a, b) => b.createdTime - a.createdTime) - } else if (sort === 'resolved') { - matches = _.sortBy( - matches, - (contract) => -1 * (contract.resolutionTime ?? 0) - ) - } else if (sort === 'oldest') { - matches.sort((a, b) => a.createdTime - b.createdTime) - } else if (sort === 'close-date' || sort === 'closed') { - matches = _.sortBy(matches, ({ volume24Hours }) => -1 * volume24Hours) - matches = _.sortBy( - matches, - (contract) => - (sort === 'closed' ? -1 : 1) * (contract.closeTime ?? Infinity) - ) - const hideClosed = sort === 'closed' - matches = matches.filter( - ({ closeTime }) => closeTime && closeTime > Date.now() !== hideClosed - ) - } else if (sort === 'most-traded') { - matches.sort((a, b) => b.volume - a.volume) - } else if (sort === '24-hour-vol') { - // Use lodash for stable sort, so previous sort breaks all ties. - matches = _.sortBy(matches, ({ volume7Days }) => -1 * volume7Days) - matches = _.sortBy(matches, ({ volume24Hours }) => -1 * volume24Hours) - } else if (sort === 'creator' || sort === 'tag') { - matches.sort((a, b) => b.volume7Days - a.volume7Days) - } else if (sort === 'most-likely') { - matches = _.sortBy(matches, (contract) => -getBinaryProb(contract)) - } else if (sort === 'least-likely') { - // Exclude non-binary contracts - matches = matches.filter((contract) => getBinaryProb(contract) !== 0) - matches = _.sortBy(matches, (contract) => getBinaryProb(contract)) - } - - if (sort !== 'all') { - // Filter for (or filter out) resolved contracts - matches = matches.filter((c) => - sort === 'resolved' ? c.resolution : !c.resolution - ) - - // Filter out closed contracts. - if (sort !== 'closed' && sort !== 'resolved') { - matches = matches.filter((c) => !c.closeTime || c.closeTime > Date.now()) - } - } - - return ( -
- {/* Show a search input next to a sort dropdown */} -
- setQuery(e.target.value)} - placeholder="Search markets" - className="input input-bordered w-full" - /> - -
- - {contracts === undefined ? ( - - ) : sort === 'tag' ? ( - - ) : !byOneCreator && sort === 'creator' ? ( - - ) : ( - - )} -
- ) -} - -export function CreatorContractsList(props: { contracts: Contract[] }) { - const { contracts } = props - return ( - diff --git a/web/components/feed-create.tsx b/web/components/feed-create.tsx index 1f308355..6d192336 100644 --- a/web/components/feed-create.tsx +++ b/web/components/feed-create.tsx @@ -1,3 +1,4 @@ +import _ from 'lodash' import { SparklesIcon, XIcon } from '@heroicons/react/solid' import { Avatar } from './avatar' import { useEffect, useRef, useState } from 'react' @@ -9,8 +10,7 @@ import { Contract, MAX_QUESTION_LENGTH } from 'common/contract' import { Col } from './layout/col' import clsx from 'clsx' import { Row } from './layout/row' -import { ENV_CONFIG } from 'common/envs/constants' -import _ from 'lodash' +import { ENV_CONFIG } from '../../common/envs/constants' import { SiteLink } from './site-link' export function FeedPromo(props: { hotContracts: Contract[] }) { @@ -50,7 +50,8 @@ export function FeedPromo(props: { hotContracts: Contract[] }) { {}} + hasMore={false} /> ) diff --git a/web/components/user-page.tsx b/web/components/user-page.tsx index a36f754c..89750b28 100644 --- a/web/components/user-page.tsx +++ b/web/components/user-page.tsx @@ -201,7 +201,7 @@ export function UserPage(props: { tabs={[ { title: 'Markets', - content: , + content: , tabIcon: (
{usersContracts.length} diff --git a/web/hooks/use-sort-and-query-params.tsx b/web/hooks/use-sort-and-query-params.tsx index 642a4e90..7a9abb85 100644 --- a/web/hooks/use-sort-and-query-params.tsx +++ b/web/hooks/use-sort-and-query-params.tsx @@ -1,22 +1,20 @@ import _ from 'lodash' import { useRouter } from 'next/router' import { useEffect, useMemo, useState } from 'react' +import { useSearchBox } from 'react-instantsearch-hooks-web' const MARKETS_SORT = 'markets_sort' export type Sort = - | 'creator' - | 'tag' | 'newest' | 'oldest' | 'most-traded' | '24-hour-vol' - | 'close-date' + | 'closing-soon' | 'closed' | 'resolved' - | 'all' -export function useQueryAndSortParams(options?: { +export function useInitialQueryAndSort(options?: { defaultSort: Sort shouldLoadFromStorage?: boolean }) { @@ -26,24 +24,58 @@ export function useQueryAndSortParams(options?: { }) const router = useRouter() - const { s: sort, q: query } = router.query as { - q?: string - s?: Sort + const [initialSort, setInitialSort] = useState(undefined) + const [initialQuery, setInitialQuery] = useState('') + + useEffect(() => { + // If there's no sort option, then set the one from localstorage + if (router.isReady) { + const { s: sort, q: query } = router.query as { + q?: string + s?: Sort + } + + setInitialQuery(query ?? '') + + if (!sort && shouldLoadFromStorage) { + console.log('ready loading from storage ', sort ?? defaultSort) + const localSort = localStorage.getItem(MARKETS_SORT) as Sort + if (localSort) { + router.query.s = localSort + // Use replace to not break navigating back. + router.replace(router, undefined, { shallow: true }) + } + setInitialSort(localSort ?? defaultSort) + } else { + console.log('ready setting to ', sort ?? defaultSort) + setInitialSort(sort ?? defaultSort) + } + } + }, [defaultSort, router.isReady, shouldLoadFromStorage]) + + return { + initialSort, + initialQuery, } +} + +export function useUpdateQueryAndSort(props: { + shouldLoadFromStorage: boolean +}) { + const { shouldLoadFromStorage } = props + const router = useRouter() const setSort = (sort: Sort | undefined) => { - router.query.s = sort - router.push(router, undefined, { shallow: true }) - if (shouldLoadFromStorage) { - localStorage.setItem(MARKETS_SORT, sort || '') + if (sort !== router.query.s) { + router.query.s = sort + router.push(router, undefined, { shallow: true }) + if (shouldLoadFromStorage) { + localStorage.setItem(MARKETS_SORT, sort || '') + } } } - const [queryState, setQueryState] = useState(query) - - useEffect(() => { - setQueryState(query) - }, [query]) + const { query, refine } = useSearchBox() // Debounce router query update. const pushQuery = useMemo( @@ -60,26 +92,13 @@ export function useQueryAndSortParams(options?: { ) const setQuery = (query: string | undefined) => { - setQueryState(query) + refine(query ?? '') pushQuery(query) } - useEffect(() => { - // If there's no sort option, then set the one from localstorage - if (router.isReady && !sort && shouldLoadFromStorage) { - const localSort = localStorage.getItem(MARKETS_SORT) as Sort - if (localSort) { - router.query.s = localSort - // Use replace to not break navigating back. - router.replace(router, undefined, { shallow: true }) - } - } - }) - return { - sort: sort ?? defaultSort, - query: queryState ?? '', setSort, setQuery, + query, } } diff --git a/web/package.json b/web/package.json index d29a01b5..6e9d6f7d 100644 --- a/web/package.json +++ b/web/package.json @@ -21,6 +21,7 @@ "@heroicons/react": "1.0.5", "@nivo/core": "0.74.0", "@nivo/line": "0.74.0", + "algoliasearch": "4.13.0", "clsx": "1.1.1", "cors": "^2.8.5", "daisyui": "1.16.4", @@ -31,9 +32,10 @@ "lodash": "4.17.21", "next": "12.1.2", "react": "17.0.2", - "react-confetti": "^6.0.1", + "react-confetti": "6.0.1", "react-dom": "17.0.2", - "react-expanding-textarea": "2.3.5" + "react-expanding-textarea": "2.3.5", + "react-instantsearch-hooks-web": "6.24.1" }, "devDependencies": { "@tailwindcss/forms": "0.4.0", diff --git a/web/pages/_document.tsx b/web/pages/_document.tsx index 461103bd..93d5d774 100644 --- a/web/pages/_document.tsx +++ b/web/pages/_document.tsx @@ -18,6 +18,13 @@ export default function Document() { rel="stylesheet" /> + +