diff --git a/.secrets.baseline b/.secrets.baseline index 9f703432046..21dd98ec663 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -206,7 +206,7 @@ "filename": "src/lib/Scenes/Onboarding/OnboardingLogin.tsx", "hashed_secret": "788d3735e304fa8e76b78c05be0ac0b3cdf353a9", "is_verified": false, - "line_number": 178 + "line_number": 194 } ], "src/lib/store/AuthModel.tests.ts": [ @@ -222,14 +222,14 @@ "filename": "src/lib/store/AuthModel.tests.ts", "hashed_secret": "54e9af600f3bcfd1153b00430b345fcb68c8efc2", "is_verified": false, - "line_number": 151 + "line_number": 153 }, { "type": "Secret Keyword", "filename": "src/lib/store/AuthModel.tests.ts", "hashed_secret": "bb21216b09d3be2d9e40beab38ae57af2b11d081", "is_verified": false, - "line_number": 287 + "line_number": 297 } ], "src/lib/utils/PushNotification.tests.ts": [ @@ -247,30 +247,30 @@ "filename": "src/setupJest.ts", "hashed_secret": "54e9af600f3bcfd1153b00430b345fcb68c8efc2", "is_verified": false, - "line_number": 527 + "line_number": 530 }, { "type": "Secret Keyword", "filename": "src/setupJest.ts", "hashed_secret": "62befb82f1107014f73b30096000b729a1018601", "is_verified": false, - "line_number": 528 + "line_number": 531 }, { "type": "Secret Keyword", "filename": "src/setupJest.ts", "hashed_secret": "34bac5b688f5b61044c219bbf8d241e52d79c2a6", "is_verified": false, - "line_number": 535 + "line_number": 538 }, { "type": "Secret Keyword", "filename": "src/setupJest.ts", "hashed_secret": "c5110328c5d8a4204c28e7415cf3db6a95239891", "is_verified": false, - "line_number": 536 + "line_number": 539 } ] }, - "generated_at": "2022-01-18T11:24:29Z" + "generated_at": "2022-01-21T11:04:42Z" } diff --git a/.vimrc b/.vimrc index 315853e89ba..eb6684f7763 100644 --- a/.vimrc +++ b/.vimrc @@ -11,8 +11,8 @@ function! ArtsyIndent() setlocal shiftwidth=4 setlocal softtabstop=4 setlocal tabstop=4 - setlocal textwidth=120 - setlocal cc=120 + setlocal textwidth=100 + setlocal cc=100 endfunction autocmd Filetype c,cpp,objc call ArtsyIndent() diff --git a/.vscode/settings.json b/.vscode/settings.json index c6d221725e1..43622320a5b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -13,8 +13,8 @@ "prettier.singleQuote": false, "prettier.trailingComma": "es5", "prettier.semi": false, - "prettier.printWidth": 120, - "editor.rulers": [120], + "prettier.printWidth": 100, + "editor.rulers": [100], "editor.tabSize": 2, "files.exclude": { "**/.git": true, diff --git a/package.json b/package.json index 8be69cee24b..9fa49b2e2f1 100644 --- a/package.json +++ b/package.json @@ -315,7 +315,7 @@ ] }, "prettier": { - "printWidth": 120, + "printWidth": 100, "semi": false, "singleQuote": false, "trailingComma": "es5", diff --git a/src/lib/AndroidApp.tsx b/src/lib/AndroidApp.tsx index 7916d601844..2f7ffb789e3 100644 --- a/src/lib/AndroidApp.tsx +++ b/src/lib/AndroidApp.tsx @@ -2,7 +2,10 @@ import { GoogleSignin } from "@react-native-google-signin/google-signin" import { GlobalStore } from "lib/store/GlobalStore" import { AdminMenuWrapper } from "lib/utils/AdminMenuWrapper" import { addTrackingProvider, track } from "lib/utils/track" -import { SEGMENT_TRACKING_PROVIDER, SegmentTrackingProvider } from "lib/utils/track/SegmentTrackingProvider" +import { + SEGMENT_TRACKING_PROVIDER, + SegmentTrackingProvider, +} from "lib/utils/track/SegmentTrackingProvider" import { useDeepLinks } from "lib/utils/useDeepLinks" import { useStripeConfig } from "lib/utils/useStripeConfig" import React, { useEffect } from "react" @@ -41,7 +44,9 @@ const Main: React.FC<{}> = track()(({}) => { const isHydrated = GlobalStore.useAppState((state) => state.sessionState.isHydrated) const isLoggedIn = GlobalStore.useAppState((state) => !!state.auth.userAccessToken) const onboardingState = GlobalStore.useAppState((state) => state.auth.onboardingState) - const forceUpdateMessage = GlobalStore.useAppState((state) => state.config.echo.forceUpdateMessage) + const forceUpdateMessage = GlobalStore.useAppState( + (state) => state.config.echo.forceUpdateMessage + ) useSentryConfig() useStripeConfig() diff --git a/src/lib/AppRegistry.tsx b/src/lib/AppRegistry.tsx index 0b30d26cfa0..99762cfb6e6 100644 --- a/src/lib/AppRegistry.tsx +++ b/src/lib/AppRegistry.tsx @@ -75,7 +75,10 @@ import { MyProfilePaymentQueryRenderer } from "./Scenes/MyProfile/MyProfilePayme import { MyProfilePaymentNewCreditCard } from "./Scenes/MyProfile/MyProfilePaymentNewCreditCard" import { MyProfilePushNotificationsQueryRenderer } from "./Scenes/MyProfile/MyProfilePushNotifications" import { MyProfileSettings } from "./Scenes/MyProfile/MyProfileSettings" -import { NewWorksForYouQueryRenderer, NewWorksForYouScreenQuery } from "./Scenes/NewWorksForYou/NewWorksForYou" +import { + NewWorksForYouQueryRenderer, + NewWorksForYouScreenQuery, +} from "./Scenes/NewWorksForYou/NewWorksForYou" import { Onboarding } from "./Scenes/Onboarding/Onboarding" import { OrderDetailsQueryRender } from "./Scenes/OrderHistory/OrderDetails/Components/OrderDetails" import { OrderHistoryQueryRender } from "./Scenes/OrderHistory/OrderHistory" @@ -97,14 +100,20 @@ import { VanityURLEntityRenderer } from "./Scenes/VanityURL/VanityURLEntity" import { ViewingRoomQueryRenderer } from "./Scenes/ViewingRoom/ViewingRoom" import { ViewingRoomArtworkScreen } from "./Scenes/ViewingRoom/ViewingRoomArtwork" import { ViewingRoomArtworksQueryRenderer } from "./Scenes/ViewingRoom/ViewingRoomArtworks" -import { ViewingRoomsListScreen, ViewingRoomsListScreenQuery } from "./Scenes/ViewingRoom/ViewingRoomsList" +import { + ViewingRoomsListScreen, + ViewingRoomsListScreenQuery, +} from "./Scenes/ViewingRoom/ViewingRoomsList" import { GlobalStore, useSelectedTab } from "./store/GlobalStore" import { propsStore } from "./store/PropsStore" import { AdminMenu } from "./utils/AdminMenu" import { useInitializeQueryPrefetching } from "./utils/queryPrefetching" import { addTrackingProvider, Schema, screenTrack, track } from "./utils/track" import { ConsoleTrackingProvider } from "./utils/track/ConsoleTrackingProvider" -import { SEGMENT_TRACKING_PROVIDER, SegmentTrackingProvider } from "./utils/track/SegmentTrackingProvider" +import { + SEGMENT_TRACKING_PROVIDER, + SegmentTrackingProvider, +} from "./utils/track/SegmentTrackingProvider" import { useExperiments } from "./utils/useExperiments" import { useFreshInstallTracking } from "./utils/useFreshInstallTracking" import { usePreferredThemeTracking } from "./utils/usePreferredThemeTracking" @@ -145,7 +154,9 @@ interface PartnerLocationsProps { safeAreaInsets: SafeAreaInsets isVisible: boolean } -const PartnerLocations: React.FC = (props) => +const PartnerLocations: React.FC = (props) => ( + +) interface InquiryProps { artworkID: string @@ -177,7 +188,12 @@ interface PageWrapperProps { moduleName: string } -const InnerPageWrapper: React.FC = ({ fullBleed, isMainView, ViewComponent, viewProps }) => { +const InnerPageWrapper: React.FC = ({ + fullBleed, + isMainView, + ViewComponent, + viewProps, +}) => { const safeAreaInsets = useScreenDimensions().safeAreaInsets const paddingTop = fullBleed ? 0 : safeAreaInsets.top const paddingBottom = isMainView ? 0 : safeAreaInsets.bottom @@ -191,7 +207,9 @@ const InnerPageWrapper: React.FC = ({ fullBleed, isMainView, V } const isPresentedModally = viewProps.isPresentedModally return ( - + {isHydrated ? ( @@ -209,7 +227,10 @@ class PageWrapper extends React.Component { render() { const props = { ...this.props, - viewProps: { ...this.props.viewProps, ...propsStore.getPropsForModule(this.props.moduleName) }, + viewProps: { + ...this.props.viewProps, + ...propsStore.getPropsForModule(this.props.moduleName), + }, } return ( @@ -356,12 +377,18 @@ export const modules = defineModules({ MyCollection: reactModule(MyCollectionQueryRenderer), MyCollectionArtwork: reactModule(MyCollectionArtworkQueryRenderer), MyCollectionArtworkFullDetails: reactModule(MyCollectionArtworkFullDetailsQueryRenderer), - MyProfile: reactModule(MyProfileQueryRenderer, { isRootViewForTabName: "profile" }, MyProfileScreenQuery), + MyProfile: reactModule( + MyProfileQueryRenderer, + { isRootViewForTabName: "profile" }, + MyProfileScreenQuery + ), MyProfilePayment: reactModule(MyProfilePaymentQueryRenderer), MyProfileSettings: reactModule(MyProfileSettings), OrderHistory: reactModule(OrderHistoryQueryRender), OrderDetails: reactModule(OrderDetailsQueryRender), - MyProfilePaymentNewCreditCard: reactModule(MyProfilePaymentNewCreditCard, { hidesBackButton: true }), + MyProfilePaymentNewCreditCard: reactModule(MyProfilePaymentNewCreditCard, { + hidesBackButton: true, + }), MyProfilePushNotifications: reactModule(MyProfilePushNotificationsQueryRenderer), MySellingProfile: reactModule(View), Partner: reactModule(PartnerQueryRenderer), @@ -387,7 +414,11 @@ export const modules = defineModules({ }), WorksForYou: reactModule(WorksForYouQueryRenderer, {}, WorksForYouScreenQuery), NewWorksForYou: reactModule(NewWorksForYouQueryRenderer, {}, NewWorksForYouScreenQuery), - LotsByArtistsYouFollow: reactModule(LotsByArtistsYouFollowQueryRenderer, {}, LotsByArtistsYouFollowScreenQuery), + LotsByArtistsYouFollow: reactModule( + LotsByArtistsYouFollowQueryRenderer, + {}, + LotsByArtistsYouFollowScreenQuery + ), Storybook: reactModule(StorybookUIRoot, { fullBleed: true, hidesBackButton: true }), SavedSearchAlertsList: reactModule(SavedSearchAlertsListQueryRenderer), EditSavedSearchAlert: reactModule(EditSavedSearchAlertQueryRenderer), @@ -398,7 +429,10 @@ for (const moduleName of Object.keys(modules)) { const descriptor = modules[moduleName as AppModule] if ("Component" in descriptor) { if (Platform.OS === "ios") { - register(moduleName, descriptor.Component, { fullBleed: descriptor.options.fullBleed, moduleName }) + register(moduleName, descriptor.Component, { + fullBleed: descriptor.options.fullBleed, + moduleName, + }) } } } @@ -417,7 +451,9 @@ const Main: React.FC<{}> = track()(({}) => { const isLoggedIn = GlobalStore.useAppState((store) => store.auth.userAccessToken) const onboardingState = GlobalStore.useAppState((state) => state.auth.onboardingState) - const forceUpdateMessage = GlobalStore.useAppState((state) => state.config.echo.forceUpdateMessage) + const forceUpdateMessage = GlobalStore.useAppState( + (state) => state.config.echo.forceUpdateMessage + ) useSentryConfig() useStripeConfig() diff --git a/src/lib/Components/AnimatableHeader/AnimatableHeader.tsx b/src/lib/Components/AnimatableHeader/AnimatableHeader.tsx index 63ae60c302f..90d76a7d11e 100644 --- a/src/lib/Components/AnimatableHeader/AnimatableHeader.tsx +++ b/src/lib/Components/AnimatableHeader/AnimatableHeader.tsx @@ -71,7 +71,8 @@ const runTiming = (clock: Clock, value: Animated.Value) => { export const AnimatableHeader: React.FC = (props) => { const { title, rightButtonDisabled, rightButtonText, onRightButtonPress } = props const { space } = useTheme() - const { scrollOffsetY, headerHeight, largeTitleHeight, largeTitleEndEdge, setTitle } = useAnimatableHeaderContext() + const { scrollOffsetY, headerHeight, largeTitleHeight, largeTitleEndEdge, setTitle } = + useAnimatableHeaderContext() const clock = useRef(new Animated.Clock()).current const value = useRef(new Animated.Value(0)).current const opacity = useRef(runTiming(clock, value)).current diff --git a/src/lib/Components/Artist/ArtistAbout/ArtistAbout.tsx b/src/lib/Components/Artist/ArtistAbout/ArtistAbout.tsx index f931d60e8a9..cad9096f9fd 100644 --- a/src/lib/Components/Artist/ArtistAbout/ArtistAbout.tsx +++ b/src/lib/Components/Artist/ArtistAbout/ArtistAbout.tsx @@ -38,9 +38,14 @@ export const ArtistAbout: React.FC = ({ artist }) => { mt={2} /> )} - {artist.notableWorks?.edges?.length === 3 && } + {artist.notableWorks?.edges?.length === 3 && ( + + )} {!!artist.iconicCollections && artist.iconicCollections.length > 1 && ( - + )} diff --git a/src/lib/Components/Artist/ArtistAbout/ArtistAboutShows.tsx b/src/lib/Components/Artist/ArtistAbout/ArtistAboutShows.tsx index f39cf72c7b1..746d24d01ae 100644 --- a/src/lib/Components/Artist/ArtistAbout/ArtistAboutShows.tsx +++ b/src/lib/Components/Artist/ArtistAbout/ArtistAboutShows.tsx @@ -58,7 +58,12 @@ const ArtistAboutShows: React.FC = ({ artist }) => { contentContainerStyle={{ paddingBottom: 15, paddingLeft: 20 }} /> {!!pastShows.length && ( - )} diff --git a/src/lib/Components/Artist/ArtistArtworks/ArtistArtworks.tsx b/src/lib/Components/Artist/ArtistArtworks/ArtistArtworks.tsx index 6be6852d173..100f8a15ef2 100644 --- a/src/lib/Components/Artist/ArtistArtworks/ArtistArtworks.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/ArtistArtworks.tsx @@ -1,13 +1,22 @@ import { OwnerType } from "@artsy/cohesion" import { ArtistArtworks_artist } from "__generated__/ArtistArtworks_artist.graphql" import { ArtworkFilterNavigator, FilterModalMode } from "lib/Components/ArtworkFilter" -import { Aggregations, filterArtworksParams } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersStoreProvider, ArtworksFiltersStore } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + Aggregations, + filterArtworksParams, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + ArtworkFiltersStoreProvider, + ArtworksFiltersStore, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { ORDERED_ARTWORK_SORTS } from "lib/Components/ArtworkFilter/Filters/SortOptions" import { convertSavedSearchCriteriaToFilterParams } from "lib/Components/ArtworkFilter/SavedSearch/convertersToFilterParams" import { getAllowedFiltersForSavedSearchInput } from "lib/Components/ArtworkFilter/SavedSearch/searchCriteriaHelpers" import { SearchCriteriaAttributes } from "lib/Components/ArtworkFilter/SavedSearch/types" -import { useArtworkFilters, useSelectedFiltersCount } from "lib/Components/ArtworkFilter/useArtworkFilters" +import { + useArtworkFilters, + useSelectedFiltersCount, +} from "lib/Components/ArtworkFilter/useArtworkFilters" import { ArtworksFilterHeader } from "lib/Components/ArtworkGrids/ArtworksFilterHeader" import { FilteredArtworkGridZeroState } from "lib/Components/ArtworkGrids/FilteredArtworkGridZeroState" import { @@ -71,7 +80,12 @@ const ArtworksGrid: React.FC = ({ artist, relay, ...props }) return ( - + state.appliedFilters) - const setInitialFilterStateAction = ArtworksFiltersStore.useStoreActions((state) => state.setInitialFilterStateAction) + const setInitialFilterStateAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setInitialFilterStateAction + ) const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations) @@ -116,7 +132,8 @@ const ArtistArtworksContainer: React.FC 0 || isEnabledImprovedAlertsFlow + const shouldShowSavedSearchButton = + allowedFiltersForSavedSearch.length > 0 || isEnabledImprovedAlertsFlow useArtworkFilters({ relay, @@ -130,7 +147,9 @@ const ArtistArtworksContainer: React.FC sortEntity.paramValue === "-published_at") + const sortFilterItem = ORDERED_ARTWORK_SORTS.find( + (sortEntity) => sortEntity.paramValue === "-published_at" + ) setInitialFilterStateAction([...params, sortFilterItem!]) } @@ -284,7 +303,12 @@ export default createPaginationContainer( } }, query: graphql` - query ArtistArtworksQuery($id: ID!, $count: Int!, $cursor: String, $input: FilterArtworksInput) { + query ArtistArtworksQuery( + $id: ID! + $count: Int! + $cursor: String + $input: FilterArtworksInput + ) { node(id: $id) { ... on Artist { ...ArtistArtworks_artist @arguments(count: $count, cursor: $cursor, input: $input) diff --git a/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tests.tsx b/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tests.tsx index c5dcae66db1..9d4dcabbfec 100644 --- a/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tests.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tests.tsx @@ -18,7 +18,10 @@ describe("Artist Series Rail", () => { return ( - + ) diff --git a/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tsx b/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tsx index d92f9165d0b..ccb35731472 100644 --- a/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/ArtistCollectionsRail.tsx @@ -38,30 +38,33 @@ const ArtistSeriesRailWrapper = styled(Box)` margin: 0 -20px 20px -40px; ` -export const ArtistCollectionsRailFragmentContainer = createFragmentContainer(ArtistCollectionsRail, { - artist: graphql` - fragment ArtistCollectionsRail_artist on Artist { - internalID - slug - } - `, +export const ArtistCollectionsRailFragmentContainer = createFragmentContainer( + ArtistCollectionsRail, + { + artist: graphql` + fragment ArtistCollectionsRail_artist on Artist { + internalID + slug + } + `, - collections: graphql` - fragment ArtistCollectionsRail_collections on MarketingCollection @relay(plural: true) { - slug - id - title - priceGuidance - artworksConnection(first: 3, aggregations: [TOTAL], sort: "-decayed_merch") { - edges { - node { - title - image { - url + collections: graphql` + fragment ArtistCollectionsRail_collections on MarketingCollection @relay(plural: true) { + slug + id + title + priceGuidance + artworksConnection(first: 3, aggregations: [TOTAL], sort: "-decayed_merch") { + edges { + node { + title + image { + url + } } } } } - } - `, -}) + `, + } +) diff --git a/src/lib/Components/Artist/ArtistArtworks/ArtistNotableWorksRail.tsx b/src/lib/Components/Artist/ArtistArtworks/ArtistNotableWorksRail.tsx index c85b04ed7a8..02a4278f5b9 100644 --- a/src/lib/Components/Artist/ArtistArtworks/ArtistNotableWorksRail.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/ArtistNotableWorksRail.tsx @@ -36,7 +36,15 @@ const ArtistNotableWorksRail: React.FC = ({ artist return } - trackEvent(tracks.tapArtwork(artist.internalID, artist.slug, artwork.internalID, artwork.slug, position)) + trackEvent( + tracks.tapArtwork( + artist.internalID, + artist.slug, + artwork.internalID, + artwork.slug, + position + ) + ) return navigate(`/artwork/${artwork.slug}`) }} @@ -51,25 +59,34 @@ const ArtistNotableWorksRailWrapper = styled(Box)` margin: 0px -20px 20px -20px; ` -export const ArtistNotableWorksRailFragmentContainer = createFragmentContainer(ArtistNotableWorksRail, { - artist: graphql` - fragment ArtistNotableWorksRail_artist on Artist { - internalID - slug - # this should match the notableWorks query in ArtistAbout - filterArtworksConnection(first: 10, input: { sort: "-weighted_iconicity" }) { - edges { - node { - ...SmallArtworkRail_artworks +export const ArtistNotableWorksRailFragmentContainer = createFragmentContainer( + ArtistNotableWorksRail, + { + artist: graphql` + fragment ArtistNotableWorksRail_artist on Artist { + internalID + slug + # this should match the notableWorks query in ArtistAbout + filterArtworksConnection(first: 10, input: { sort: "-weighted_iconicity" }) { + edges { + node { + ...SmallArtworkRail_artworks + } } } } - } - `, -}) + `, + } +) export const tracks = { - tapArtwork: (artistId: string, artistSlug: string, artworkId: string, artworkSlug: string, position: number) => ({ + tapArtwork: ( + artistId: string, + artistSlug: string, + artworkId: string, + artworkSlug: string, + position: number + ) => ({ action: ActionType.tappedArtworkGroup, context_module: ContextModule.topWorksRail, context_screen_owner_type: OwnerType.artist, diff --git a/src/lib/Components/Artist/ArtistArtworks/CreateSavedSearchModal.tests.tsx b/src/lib/Components/Artist/ArtistArtworks/CreateSavedSearchModal.tests.tsx index 66fda972519..a4e724ce946 100644 --- a/src/lib/Components/Artist/ArtistArtworks/CreateSavedSearchModal.tests.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/CreateSavedSearchModal.tests.tsx @@ -1,5 +1,8 @@ import { fireEvent } from "@testing-library/react-native" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { navigate } from "lib/navigation/navigate" import { CreateSavedSearchAlert } from "lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert" import { SavedSearchAlertMutationResult } from "lib/Scenes/SavedSearchAlert/SavedSearchAlertModel" @@ -8,7 +11,11 @@ import { mockTrackEvent } from "lib/tests/globallyMockedStuff" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import { delay } from "lib/utils/delay" import React from "react" -import { CreateSavedSearchModal, CreateSavedSearchModalProps, tracks } from "./CreateSavedSearchModal" +import { + CreateSavedSearchModal, + CreateSavedSearchModalProps, + tracks, +} from "./CreateSavedSearchModal" jest.unmock("react-relay") diff --git a/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tests.tsx b/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tests.tsx index 30f93dd7078..e61abf77980 100644 --- a/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tests.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tests.tsx @@ -46,7 +46,8 @@ describe("SavedSearchButton", () => { environment={mockEnvironment} query={graphql` - query SavedSearchButtonTestsQuery($criteria: SearchCriteriaAttributes!) @relay_test_operation { + query SavedSearchButtonTestsQuery($criteria: SearchCriteriaAttributes!) + @relay_test_operation { me { ...SavedSearchButton_me @arguments(criteria: $criteria) } @@ -134,7 +135,9 @@ describe("SavedSearchButton", () => { it("should navigate to the saved search alerts list when popover is pressed", async () => { const tree = renderWithWrappers() - act(() => tree.root.findByType(CreateSavedSearchAlert).props.params.onComplete(mockedMutationResult)) + act(() => + tree.root.findByType(CreateSavedSearchAlert).props.params.onComplete(mockedMutationResult) + ) act(() => tree.root.findByType(PopoverMessage).props.onPress()) expect(navigate).toHaveBeenCalledWith("/my-profile/settings", { @@ -148,7 +151,9 @@ describe("SavedSearchButton", () => { __globalStoreTestUtils__?.injectFeatureFlags({ AREnableMyCollectionIOS: true }) const tree = renderWithWrappers() - act(() => tree.root.findByType(CreateSavedSearchAlert).props.params.onComplete(mockedMutationResult)) + act(() => + tree.root.findByType(CreateSavedSearchAlert).props.params.onComplete(mockedMutationResult) + ) act(() => tree.root.findByType(PopoverMessage).props.onPress()) jest.runAllTimers() @@ -163,7 +168,9 @@ describe("SavedSearchButton", () => { it("tracks clicks when the create alert button is pressed", async () => { const tree = renderWithWrappers() - act(() => tree.root.findByType(CreateSavedSearchAlert).props.params.onComplete(mockedMutationResult)) + act(() => + tree.root.findByType(CreateSavedSearchAlert).props.params.onComplete(mockedMutationResult) + ) expect(mockTrackEvent).toHaveBeenCalledWith( tracks.toggleSavedSearch(true, "artistID", "artistSlug", "savedSearchAlertId") diff --git a/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tsx b/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tsx index 71e61c5af6b..4e947f395b3 100644 --- a/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/SavedSearchButton.tsx @@ -149,7 +149,8 @@ export const SavedSearchButtonRefetchContainer = createRefetchContainer( SavedSearchButton, { me: graphql` - fragment SavedSearchButton_me on Me @argumentDefinitions(criteria: { type: "SearchCriteriaAttributes" }) { + fragment SavedSearchButton_me on Me + @argumentDefinitions(criteria: { type: "SearchCriteriaAttributes" }) { ...CreateSavedSearchContentContainerV1_me savedSearch(criteria: $criteria) { internalID @@ -166,9 +167,14 @@ export const SavedSearchButtonRefetchContainer = createRefetchContainer( ` ) -export const SavedSearchButtonQueryRenderer: React.FC = (props) => { +export const SavedSearchButtonQueryRenderer: React.FC = ( + props +) => { const { filters, artistId } = props - const criteria = useMemo(() => getSearchCriteriaFromFilters(artistId, filters), [artistId, filters]) + const criteria = useMemo( + () => getSearchCriteriaFromFilters(artistId, filters), + [artistId, filters] + ) return ( diff --git a/src/lib/Components/Artist/ArtistArtworks/SavedSearchButtonV2.tests.tsx b/src/lib/Components/Artist/ArtistArtworks/SavedSearchButtonV2.tests.tsx index 126fa0471ef..58dfc5686d0 100644 --- a/src/lib/Components/Artist/ArtistArtworks/SavedSearchButtonV2.tests.tsx +++ b/src/lib/Components/Artist/ArtistArtworks/SavedSearchButtonV2.tests.tsx @@ -6,7 +6,14 @@ import { SavedSearchButtonV2, SavedSearchButtonV2Props } from "./SavedSearchButt describe("SavedSearchButtonV2", () => { const TestWrapper = (props: Partial) => { - return + return ( + + ) } it("renders without error", () => { diff --git a/src/lib/Components/Artist/ArtistConsignButton.tests.tsx b/src/lib/Components/Artist/ArtistConsignButton.tests.tsx index 6bfa244b8c1..2c4ef06c57d 100644 --- a/src/lib/Components/Artist/ArtistConsignButton.tests.tsx +++ b/src/lib/Components/Artist/ArtistConsignButton.tests.tsx @@ -68,7 +68,9 @@ describe("ArtistConsignButton", () => { it("renders microfunnel correctly", () => { const tree = renderWithWrappers() - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("ArtistConsignButtonTestsQuery") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "ArtistConsignButtonTestsQuery" + ) act(() => { env.mock.resolveMostRecentOperation({ errors: [], @@ -81,7 +83,9 @@ describe("ArtistConsignButton", () => { it("renders target supply correctly", () => { const tree = renderWithWrappers() - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("ArtistConsignButtonTestsQuery") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "ArtistConsignButtonTestsQuery" + ) act(() => { const targetSupplyResponse = cloneDeep(response) targetSupplyResponse.artist.targetSupply.isInMicrofunnel = false @@ -214,7 +218,9 @@ describe("ArtistConsignButton", () => { }) tree.root.findByType(TouchableOpacity).props.onPress() - expect(navigate).toHaveBeenCalledWith("/sales", { passProps: { overwriteHardwareBackButtonPath: "search" } }) + expect(navigate).toHaveBeenCalledWith("/sales", { + passProps: { overwriteHardwareBackButtonPath: "search" }, + }) }) it("sends user to a new instance of landing page if user is already in sales tab", () => { diff --git a/src/lib/Components/Artist/ArtistConsignButton.tsx b/src/lib/Components/Artist/ArtistConsignButton.tsx index a9283bc4282..1e05296a81c 100644 --- a/src/lib/Components/Artist/ArtistConsignButton.tsx +++ b/src/lib/Components/Artist/ArtistConsignButton.tsx @@ -32,7 +32,9 @@ export const ArtistConsignButton: React.FC = (props) = { - const destination: string = isSalesTab ? "/collections/my-collection/marketing-landing" : "/sales" + const destination: string = isSalesTab + ? "/collections/my-collection/marketing-landing" + : "/sales" tracking.trackEvent({ context_page: Schema.PageNames.ArtistPage, diff --git a/src/lib/Components/Artist/ArtistHeader.tsx b/src/lib/Components/Artist/ArtistHeader.tsx index f8b1167d7c2..e4218c56bea 100644 --- a/src/lib/Components/Artist/ArtistHeader.tsx +++ b/src/lib/Components/Artist/ArtistHeader.tsx @@ -42,7 +42,9 @@ export const ArtistHeader: React.FC = ({ artist, relay }) => { const handleFollowChange = () => { trackEvent({ - action_name: artist.isFollowed ? Schema.ActionNames.ArtistUnfollow : Schema.ActionNames.ArtistFollow, + action_name: artist.isFollowed + ? Schema.ActionNames.ArtistUnfollow + : Schema.ActionNames.ArtistFollow, action_type: Schema.ActionTypes.Tap, owner_id: artist.internalID, owner_slug: artist.slug, @@ -88,7 +90,9 @@ export const ArtistHeader: React.FC = ({ artist, relay }) => { const successfulFollowChange = () => { trackEvent({ - action_name: artist.isFollowed ? Schema.ActionNames.ArtistUnfollow : Schema.ActionNames.ArtistFollow, + action_name: artist.isFollowed + ? Schema.ActionNames.ArtistUnfollow + : Schema.ActionNames.ArtistFollow, action_type: Schema.ActionTypes.Success, owner_id: artist.internalID, owner_slug: artist.slug, @@ -107,7 +111,9 @@ export const ArtistHeader: React.FC = ({ artist, relay }) => { const failedFollowChange = () => { trackEvent({ - action_name: artist.isFollowed ? Schema.ActionNames.ArtistFollow : Schema.ActionNames.ArtistUnfollow, + action_name: artist.isFollowed + ? Schema.ActionNames.ArtistFollow + : Schema.ActionNames.ArtistUnfollow, action_type: Schema.ActionTypes.Fail, owner_id: artist.internalID, owner_slug: artist.slug, diff --git a/src/lib/Components/Artist/ArtistHeaderFloatingButtons.tsx b/src/lib/Components/Artist/ArtistHeaderFloatingButtons.tsx index 9d35c77ab0a..5b099800f25 100644 --- a/src/lib/Components/Artist/ArtistHeaderFloatingButtons.tsx +++ b/src/lib/Components/Artist/ArtistHeaderFloatingButtons.tsx @@ -71,7 +71,9 @@ const runTiming = (clock: Clock, value: Animated.Value) => { ]) } -export const ArtistHeaderFloatingButtons: React.FC = ({ artist }) => { +export const ArtistHeaderFloatingButtons: React.FC = ({ + artist, +}) => { const [shareSheetVisible, setShareSheetVisible] = useState(false) const [hideButton, setHideButton] = useState(false) const { headerOffsetY } = useStickyTabPageContext() @@ -134,16 +136,19 @@ export const ArtistHeaderFloatingButtons: React.FC = (props) => { onScrollEndDrag={onScrollEndDrag} innerRef={flatListRef} > - + = (props) => { auctionResultsYCoordinate.current = y }} > - + { }), }) - expect(extractText(tree.root.findByType(SortMode))).toBe("1 result • Sorted by most recent sale date") + expect(extractText(tree.root.findByType(SortMode))).toBe( + "1 result • Sorted by most recent sale date" + ) }) it("renders the results string when totalCount is greater than 1", () => { @@ -117,7 +125,9 @@ describe("ArtistInsightsAuctionResults", () => { }, }), }) - expect(extractText(tree.root.findByType(SortMode))).toBe("10 results • Sorted by most recent sale date") + expect(extractText(tree.root.findByType(SortMode))).toBe( + "10 results • Sorted by most recent sale date" + ) }) }) }) diff --git a/src/lib/Components/Artist/ArtistInsights/ArtistInsightsAuctionResults.tsx b/src/lib/Components/Artist/ArtistInsights/ArtistInsightsAuctionResults.tsx index 266b02b0fd3..cad3a687a6c 100644 --- a/src/lib/Components/Artist/ArtistInsights/ArtistInsightsAuctionResults.tsx +++ b/src/lib/Components/Artist/ArtistInsights/ArtistInsightsAuctionResults.tsx @@ -1,6 +1,9 @@ import { ActionType, ContextModule, OwnerType, TappedInfoBubble } from "@artsy/cohesion" import { ArtistInsightsAuctionResults_artist } from "__generated__/ArtistInsightsAuctionResults_artist.graphql" -import { filterArtworksParams, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + filterArtworksParams, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { ArtworksFiltersStore } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { ORDERED_AUCTION_RESULTS_SORTS } from "lib/Components/ArtworkFilter/Filters/SortOptions" import { useArtworkFilters } from "lib/Components/ArtworkFilter/useArtworkFilters" @@ -33,11 +36,15 @@ const ArtistInsightsAuctionResults: React.FC = ({ artist, relay, scrollTo const auctionResults = extractNodes(artist.auctionResultsConnection) - const setFilterTypeAction = ArtworksFiltersStore.useStoreActions((state) => state.setFilterTypeAction) + const setFilterTypeAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setFilterTypeAction + ) const appliedFilters = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) const filterParams = filterArtworksParams(appliedFilters, "auctionResult") - const keywordFilterValue = appliedFilters?.find((filter) => filter.paramName === FilterParamName.keyword)?.paramValue + const keywordFilterValue = appliedFilters?.find( + (filter) => filter.paramName === FilterParamName.keyword + )?.paramValue const isKeywordFilterActive = !!keywordFilterValue const [loadingMoreData, setLoadingMoreData] = useState(false) @@ -64,7 +71,8 @@ const ArtistInsightsAuctionResults: React.FC = ({ artist, relay, scrollTo slice: "latestCreatedYear", counts: [ { - value: artist.auctionResultsConnection?.createdYearRange?.endAt || new Date().getFullYear(), + value: + artist.auctionResultsConnection?.createdYearRange?.endAt || new Date().getFullYear(), name: "latestCreatedYear", }, ], @@ -85,7 +93,9 @@ const ArtistInsightsAuctionResults: React.FC = ({ artist, relay, scrollTo }, []) const getSortDescription = useCallback(() => { - const sortMode = ORDERED_AUCTION_RESULTS_SORTS.find((sort) => sort.paramValue === filterParams?.sort) + const sortMode = ORDERED_AUCTION_RESULTS_SORTS.find( + (sort) => sort.paramValue === filterParams?.sort + ) if (sortMode) { return sortMode.displayText } @@ -108,19 +118,20 @@ const ArtistInsightsAuctionResults: React.FC = ({ artist, relay, scrollTo <> - These auction results bring together sale data from top auction houses around the world, including Christie’s, - Sotheby’s, Phillips and Bonhams. Results are updated daily. + These auction results bring together sale data from top auction houses around the world, + including Christie’s, Sotheby’s, Phillips and Bonhams. Results are updated daily. - Please note that the sale price includes the hammer price and buyer’s premium, as well as any other additional - fees (e.g., Artist’s Resale Rights). + Please note that the sale price includes the hammer price and buyer’s premium, as well as + any other additional fees (e.g., Artist’s Resale Rights). ) - const resultsString = Number(artist.auctionResultsConnection?.totalCount) === 1 ? "result" : "results" + const resultsString = + Number(artist.auctionResultsConnection?.totalCount) === 1 ? "result" : "results" return ( = ({ artist, relay, scrollTo ) : ( - + )} diff --git a/src/lib/Components/Artist/ArtistInsights/MarketStats.tests.tsx b/src/lib/Components/Artist/ArtistInsights/MarketStats.tests.tsx index 79d51520ff9..afc53fc2881 100644 --- a/src/lib/Components/Artist/ArtistInsights/MarketStats.tests.tsx +++ b/src/lib/Components/Artist/ArtistInsights/MarketStats.tests.tsx @@ -57,7 +57,9 @@ describe("MarketStats", () => { describe("median sale over estimate icons", () => { function renderWithOnePriceInsightNode( - nodeSpecs: Partial[0]>["node"]> + nodeSpecs: Partial< + NonNullable[0]>["node"] + > ) { const tree = renderWithWrappers().root const priceInsights = { diff --git a/src/lib/Components/Artist/ArtistInsights/MarketStats.tsx b/src/lib/Components/Artist/ArtistInsights/MarketStats.tsx index 3e4ae5611ef..7a8777df459 100644 --- a/src/lib/Components/Artist/ArtistInsights/MarketStats.tsx +++ b/src/lib/Components/Artist/ArtistInsights/MarketStats.tsx @@ -43,18 +43,19 @@ const MarketStats: React.FC = ({ priceInsightsConnection }) => - The following data points provide an overview of an artist’s auction market for a specific medium (e.g., - photography, painting) over the past 36 months. + The following data points provide an overview of an artist’s auction market for a specific + medium (e.g., photography, painting) over the past 36 months. - These market signals bring together data from top auction houses around the world, including Christie’s, - Sotheby’s, Phillips and Bonhams. + These market signals bring together data from top auction houses around the world, including + Christie’s, Sotheby’s, Phillips and Bonhams. - In this data set, please note that the sale price includes the hammer price and buyer’s premium, as well as any - other additional fees (e.g., Artist’s Resale Rights). The data set only includes works valued over $1,000. + In this data set, please note that the sale price includes the hammer price and buyer’s + premium, as well as any other additional fees (e.g., Artist’s Resale Rights). The data set + only includes works valued over $1,000. Average yearly lots sold @@ -72,20 +73,23 @@ const MarketStats: React.FC = ({ priceInsightsConnection }) => Sale price over estimate - The average percentage difference of the sale price over the mid-estimate (the midpoint of the low and high - estimates set by the auction house before the auction takes place) for lots sold at auction over the past 36 - months. + The average percentage difference of the sale price over the mid-estimate (the midpoint of + the low and high estimates set by the auction house before the auction takes place) for lots + sold at auction over the past 36 months. ) const averageValueSold = - (selectedPriceInsight.annualValueSoldCents as number) / 100 / (selectedPriceInsight.annualLotsSold || 1) + (selectedPriceInsight.annualValueSoldCents as number) / + 100 / + (selectedPriceInsight.annualLotsSold || 1) const formattedAverageValueSold = formatLargeNumber(averageValueSold) let deltaIcon: React.ReactNode - const actualMedianSaleOverEstimatePercentage = selectedPriceInsight?.medianSaleOverEstimatePercentage || 0 + const actualMedianSaleOverEstimatePercentage = + selectedPriceInsight?.medianSaleOverEstimatePercentage || 0 if (actualMedianSaleOverEstimatePercentage < 0) { deltaIcon = } else if (actualMedianSaleOverEstimatePercentage > 0) { @@ -185,7 +189,10 @@ export const MarketStatsQueryRenderer: React.FC<{ variables={{ artistInternalID }} query={graphql` query MarketStatsQuery($artistInternalID: ID!) { - priceInsightsConnection: priceInsights(artistId: $artistInternalID, sort: ANNUAL_VALUE_SOLD_CENTS_DESC) { + priceInsightsConnection: priceInsights( + artistId: $artistInternalID + sort: ANNUAL_VALUE_SOLD_CENTS_DESC + ) { ...MarketStats_priceInsightsConnection } } diff --git a/src/lib/Components/Artist/ArtistShows/ArtistShow.tests.tsx b/src/lib/Components/Artist/ArtistShows/ArtistShow.tests.tsx index a16134c109f..57da66d4841 100644 --- a/src/lib/Components/Artist/ArtistShows/ArtistShow.tests.tsx +++ b/src/lib/Components/Artist/ArtistShows/ArtistShow.tests.tsx @@ -45,5 +45,7 @@ it("renders without throwing an error with null show kind", () => { kind: null, } - renderWithWrappers() + renderWithWrappers( + + ) }) diff --git a/src/lib/Components/ArtistListItem.tsx b/src/lib/Components/ArtistListItem.tsx index ecaed61f033..60772d44d68 100644 --- a/src/lib/Components/ArtistListItem.tsx +++ b/src/lib/Components/ArtistListItem.tsx @@ -24,7 +24,11 @@ interface State { isFollowedChanging: boolean } -export const formatTombstoneText = (nationality: string | null, birthday: string | null, deathday: string | null) => { +export const formatTombstoneText = ( + nationality: string | null, + birthday: string | null, + deathday: string | null +) => { if (nationality && birthday && deathday) { return nationality.trim() + ", " + birthday + "-" + deathday } else if (nationality && birthday) { @@ -77,7 +81,9 @@ export class ArtistListItem extends React.Component { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @track((props: Props) => ({ - action_name: props.artist.is_followed ? Schema.ActionNames.ArtistFollow : Schema.ActionNames.ArtistUnfollow, + action_name: props.artist.is_followed + ? Schema.ActionNames.ArtistFollow + : Schema.ActionNames.ArtistUnfollow, action_type: Schema.ActionTypes.Success, owner_id: props.artist.internalID, owner_slug: props.artist.slug, @@ -136,7 +142,11 @@ export class ArtistListItem extends React.Component { /> - + diff --git a/src/lib/Components/ArtsyKeyboardAvoidingView.tsx b/src/lib/Components/ArtsyKeyboardAvoidingView.tsx index 06bd83cdf7f..3ca0b6a6ac6 100644 --- a/src/lib/Components/ArtsyKeyboardAvoidingView.tsx +++ b/src/lib/Components/ArtsyKeyboardAvoidingView.tsx @@ -28,7 +28,9 @@ export const ArtsyKeyboardAvoidingViewContext = React.createContext({ }) export const ArtsyKeyboardAvoidingView: React.FC<{}> = ({ children }) => { - const { isPresentedModally, isVisible, bottomOffset } = useContext(ArtsyKeyboardAvoidingViewContext) + const { isPresentedModally, isVisible, bottomOffset } = useContext( + ArtsyKeyboardAvoidingViewContext + ) return ( ({ describe(ArtsyReactWebViewPage, () => { const render = (props: Partial> = {}) => renderWithWrappers() - const webViewProps = (tree: ReturnType) => tree.root.findByType(WebView).props as WebViewProps + const webViewProps = (tree: ReturnType) => + tree.root.findByType(WebView).props as WebViewProps beforeEach(() => { __globalStoreTestUtils__?.injectFeatureFlags({ AROptionsUseReactNativeWebView: true }) }) @@ -67,7 +68,9 @@ describe(ArtsyReactWebViewPage, () => { expect(getProgressBar().children).toHaveLength(0) act(() => tree.root.findByType(WebView).props.onLoadStart()) expect(getProgressBar().children).toHaveLength(1) - act(() => tree.root.findByType(WebView).props.onLoadProgress({ nativeEvent: { progress: 0.5 } })) + act(() => + tree.root.findByType(WebView).props.onLoadProgress({ nativeEvent: { progress: 0.5 } }) + ) expect(getProgressBar().findByProps({ testID: "progress-bar" }).props.width).toBe("50%") act(() => tree.root.findByType(WebView).props.onLoadEnd()) expect(getProgressBar().children).toHaveLength(0) @@ -183,7 +186,9 @@ describe(useWebViewCookies, () => { return null } it("tries to make an authenticated HEAD request to force and prediction to make sure we get the user's coookies", () => { - __globalStoreTestUtils__?.injectState({ native: { sessionState: { authenticationToken: "userAccessToken" } } }) + __globalStoreTestUtils__?.injectState({ + native: { sessionState: { authenticationToken: "userAccessToken" } }, + }) act(() => { renderWithWrappers() }) @@ -199,7 +204,9 @@ describe(useWebViewCookies, () => { }) }) it("retries if it fails", async () => { - __globalStoreTestUtils__?.injectState({ native: { sessionState: { authenticationToken: "userAccessToken" } } }) + __globalStoreTestUtils__?.injectState({ + native: { sessionState: { authenticationToken: "userAccessToken" } }, + }) mockFetch.mockReturnValue(Promise.resolve({ ok: false, status: 500 } as any)) const tree = renderWithWrappers() await act(() => undefined) @@ -236,8 +243,10 @@ describe(__webViewTestUtils__?.expandGoogleAdLink!, () => { }) it("expands google ad links with url params", () => { - const targetURL = "https://www.artsy.net/search?" + stringify({ query: "Hello World &hello=world" }) - const googleURL = "https://googleads.g.doubleclick.net/pcs/click?" + stringify({ adurl: targetURL }) + const targetURL = + "https://www.artsy.net/search?" + stringify({ query: "Hello World &hello=world" }) + const googleURL = + "https://googleads.g.doubleclick.net/pcs/click?" + stringify({ adurl: targetURL }) const expanded = __webViewTestUtils__?.expandGoogleAdLink(googleURL) expect(expanded).toBe(targetURL) diff --git a/src/lib/Components/ArtsyReactWebView.tsx b/src/lib/Components/ArtsyReactWebView.tsx index 9865e869b83..6edcf6cf225 100644 --- a/src/lib/Components/ArtsyReactWebView.tsx +++ b/src/lib/Components/ArtsyReactWebView.tsx @@ -3,7 +3,12 @@ import { addBreadcrumb } from "@sentry/react-native" import { dismissModal, goBack, navigate } from "lib/navigation/navigate" import { matchRoute } from "lib/navigation/routes" import { BottomTabRoutes } from "lib/Scenes/BottomTabs/bottomTabsConfig" -import { getCurrentEmissionState, GlobalStore, useDevToggle, useEnvironment } from "lib/store/GlobalStore" +import { + getCurrentEmissionState, + GlobalStore, + useDevToggle, + useEnvironment, +} from "lib/store/GlobalStore" import { Schema } from "lib/utils/track" import { useScreenDimensions } from "lib/utils/useScreenDimensions" import { Flex, Text } from "palette" @@ -108,7 +113,9 @@ export const ArtsyReactWebViewPage: React.FC< } } useShareButton={showShareButton} - onRightButtonPress={showShareButton || useRightCloseButton ? onRightButtonPress : undefined} + onRightButtonPress={ + showShareButton || useRightCloseButton ? onRightButtonPress : undefined + } > {title} @@ -138,85 +145,104 @@ export const ArtsyReactWebView = React.forwardRef< onNavigationStateChange?: WebViewProps["onNavigationStateChange"] isPresentedModally?: boolean } ->(({ url, allowWebViewInnerNavigation = true, onNavigationStateChange, isPresentedModally = false }, ref) => { - const userAgent = getCurrentEmissionState().userAgent +>( + ( + { + url, + allowWebViewInnerNavigation = true, + onNavigationStateChange, + isPresentedModally = false, + }, + ref + ) => { + const userAgent = getCurrentEmissionState().userAgent - const [loadProgress, setLoadProgress] = useState(null) - const showIndicator = useDevToggle("DTShowWebviewIndicator") + const [loadProgress, setLoadProgress] = useState(null) + const showIndicator = useDevToggle("DTShowWebviewIndicator") - const webURL = useEnvironment().webURL - const uri = url.startsWith("/") ? webURL + url : url + const webURL = useEnvironment().webURL + const uri = url.startsWith("/") ? webURL + url : url - return ( - - setLoadProgress((p) => Math.max(0.02, p ?? 0))} - onLoadEnd={() => setLoadProgress(null)} - onLoadProgress={(e) => { - // we don't want to set load progress after navigating away from this - // web view (in onShouldStartLoadWithRequest). So we set - // loadProgress to null after navigating to another screen, and we - // check for that case here. - if (loadProgress !== null) { - setLoadProgress(e.nativeEvent.progress) - } - }} - onShouldStartLoadWithRequest={(ev) => { - const targetURL = expandGoogleAdLink(ev.url) - const result = matchRoute(targetURL) - // On android onShouldStartLoadWithRequest is only called for actual navigation requests - // On iOS it is also called for other-origin script/resource requests, so we use - // isTopFrame to check that this request pertains to an actual navigation request - const isTopFrame = Platform.OS === "android" ? true : ev.isTopFrame - if (!isTopFrame || targetURL === uri) { - // we use `|| targetURL === uri` because otherwise, if the URI points to a - // page that can be handled natively, we'll jump directly out of a the web view. - return true - } + return ( + + setLoadProgress((p) => Math.max(0.02, p ?? 0))} + onLoadEnd={() => setLoadProgress(null)} + onLoadProgress={(e) => { + // we don't want to set load progress after navigating away from this + // web view (in onShouldStartLoadWithRequest). So we set + // loadProgress to null after navigating to another screen, and we + // check for that case here. + if (loadProgress !== null) { + setLoadProgress(e.nativeEvent.progress) + } + }} + onShouldStartLoadWithRequest={(ev) => { + const targetURL = expandGoogleAdLink(ev.url) + const result = matchRoute(targetURL) + // On android onShouldStartLoadWithRequest is only called for actual navigation requests + // On iOS it is also called for other-origin script/resource requests, so we use + // isTopFrame to check that this request pertains to an actual navigation request + const isTopFrame = Platform.OS === "android" ? true : ev.isTopFrame + if (!isTopFrame || targetURL === uri) { + // we use `|| targetURL === uri` because otherwise, if the URI points to a + // page that can be handled natively, we'll jump directly out of a the web view. + return true + } - // If the target URL points to another page that we can handle with a web view, let's go there - if (allowWebViewInnerNavigation && result.type === "match" && result.module === "ReactWebView") { - if (ref) { - ;(ref as any).current.shareTitleUrl = targetURL + // If the target URL points to another page that we can handle with a web view, let's go there + if ( + allowWebViewInnerNavigation && + result.type === "match" && + result.module === "ReactWebView" + ) { + if (ref) { + ;(ref as any).current.shareTitleUrl = targetURL + } + return true } - return true - } - // In case of a webview presentaed modally, if the targetURL is a tab View, - // we need to dismiss the modal first to avoid having a tab rendered within the modal - const modulePathName = parseURL(targetURL).pathname?.split(/\/+/).filter(Boolean) ?? [] - if ( - isPresentedModally && - result.type === "match" && - modulePathName.length > 0 && - BottomTabRoutes.includes("/" + modulePathName[0]) - ) { - dismissModal() - } - // Otherwise use `navigate` to handle it like any other link in the app - navigate(targetURL) - setLoadProgress(null) - return false - }} - onNavigationStateChange={onNavigationStateChange} - /> - - {showIndicator ? ( - - webview - - ) : null} - - ) -}) + // In case of a webview presentaed modally, if the targetURL is a tab View, + // we need to dismiss the modal first to avoid having a tab rendered within the modal + const modulePathName = parseURL(targetURL).pathname?.split(/\/+/).filter(Boolean) ?? [] + if ( + isPresentedModally && + result.type === "match" && + modulePathName.length > 0 && + BottomTabRoutes.includes("/" + modulePathName[0]) + ) { + dismissModal() + } + // Otherwise use `navigate` to handle it like any other link in the app + navigate(targetURL) + setLoadProgress(null) + return false + }} + onNavigationStateChange={onNavigationStateChange} + /> + + {showIndicator ? ( + + webview + + ) : null} + + ) + } +) const ProgressBar: React.FC<{ loadProgress: number | null }> = ({ loadProgress }) => { if (loadProgress === null) { @@ -281,7 +307,9 @@ class CookieRequestAttempt { if (this.invalidated) { return } - addBreadcrumb({ message: `Retrying to set up artsy web view cookies in 20 seconds ${this.url}` }) + addBreadcrumb({ + message: `Retrying to set up artsy web view cookies in 20 seconds ${this.url}`, + }) setTimeout(() => this.makeAttempt(), 1000 * 20) } } diff --git a/src/lib/Components/ArtsyWebView.tsx b/src/lib/Components/ArtsyWebView.tsx index 93c199f9a1c..28b891a81c8 100644 --- a/src/lib/Components/ArtsyWebView.tsx +++ b/src/lib/Components/ArtsyWebView.tsx @@ -3,7 +3,10 @@ import React from "react" import { ArtsyReactWebView } from "./ArtsyReactWebView" import InternalWebView from "./InternalWebView" -export const ArtsyWebView: React.FC<{ url: string; showFullScreen?: boolean }> = ({ url, showFullScreen }) => { +export const ArtsyWebView: React.FC<{ url: string; showFullScreen?: boolean }> = ({ + url, + showFullScreen, +}) => { const useReactNativeWebView = useFeatureFlag("AROptionsUseReactNativeWebView") if (useReactNativeWebView) { diff --git a/src/lib/Components/ArtworkFilter/ArtworkFilterHelpers.ts b/src/lib/Components/ArtworkFilter/ArtworkFilterHelpers.ts index 4c74b046b50..dd832f6a9fb 100644 --- a/src/lib/Components/ArtworkFilter/ArtworkFilterHelpers.ts +++ b/src/lib/Components/ArtworkFilter/ArtworkFilterHelpers.ts @@ -198,7 +198,10 @@ export type SelectedFiltersCounts = { [Name in FilterParamName | "waysToBuy" | "year"]: number } -export const filterKeyFromAggregation: Record = { +export const filterKeyFromAggregation: Record< + AggregationName, + FilterParamName | string | undefined +> = { ARTIST_NATIONALITY: FilterParamName.artistNationalities, ARTIST: "artistIDs", COLOR: FilterParamName.colors, @@ -253,7 +256,10 @@ const DEFAULT_TAG_ARTWORK_PARAMS = { sort: "-partner_updated_at", } as FilterParams -const createdYearsFilterNames = [FilterParamName.earliestCreatedYear, FilterParamName.latestCreatedYear] +const createdYearsFilterNames = [ + FilterParamName.earliestCreatedYear, + FilterParamName.latestCreatedYear, +] const sizesFilterNames = [FilterParamName.width, FilterParamName.height] const waysToBuyFilterNames = [ @@ -275,7 +281,10 @@ const getDefaultParamsByType = (filterType: FilterType) => { }[filterType] } -export const changedFiltersParams = (currentFilterParams: FilterParams, selectedFilterOptions: FilterArray) => { +export const changedFiltersParams = ( + currentFilterParams: FilterParams, + selectedFilterOptions: FilterArray +) => { const changedFilters: { [key: string]: any } = {} selectedFilterOptions.forEach((selectedFilterOption) => { @@ -292,7 +301,10 @@ export const changedFiltersParams = (currentFilterParams: FilterParams, selected return changedFilters } -export const filterArtworksParams = (appliedFilters: FilterArray, filterType: FilterType = "artwork") => { +export const filterArtworksParams = ( + appliedFilters: FilterArray, + filterType: FilterType = "artwork" +) => { const defaultFilterParams = getDefaultParamsByType(filterType) const appliedFilterParams: Partial = {} diff --git a/src/lib/Components/ArtworkFilter/ArtworkFilterNavigator.tsx b/src/lib/Components/ArtworkFilter/ArtworkFilterNavigator.tsx index ff8278d3ae4..4137b541c3e 100644 --- a/src/lib/Components/ArtworkFilter/ArtworkFilterNavigator.tsx +++ b/src/lib/Components/ArtworkFilter/ArtworkFilterNavigator.tsx @@ -33,7 +33,10 @@ import { View, ViewProps } from "react-native" import { useTracking } from "react-tracking" import { CreateSavedSearchModal } from "../Artist/ArtistArtworks/CreateSavedSearchModal" import { FancyModal } from "../FancyModal/FancyModal" -import { ArtworkFilterOptionsScreen, FilterModalMode as ArtworkFilterMode } from "./ArtworkFilterOptionsScreen" +import { + ArtworkFilterOptionsScreen, + FilterModalMode as ArtworkFilterMode, +} from "./ArtworkFilterOptionsScreen" import { ArtworkFilterApplyButton } from "./components/ArtworkFilterApplyButton" import { AuctionHouseOptionsScreen } from "./Filters/AuctionHouseOptions" import { LocationCitiesOptionsScreen } from "./Filters/LocationCitiesOptions" @@ -99,11 +102,17 @@ export const ArtworkFilterNavigator: React.FC = (props) => { const appliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) const selectedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.selectedFilters) - const previouslyAppliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.previouslyAppliedFilters) + const previouslyAppliedFiltersState = ArtworksFiltersStore.useStoreState( + (state) => state.previouslyAppliedFilters + ) const filterTypeState = ArtworksFiltersStore.useStoreState((state) => state.filterType) - const applyFiltersAction = ArtworksFiltersStore.useStoreActions((action) => action.applyFiltersAction) - const resetFiltersAction = ArtworksFiltersStore.useStoreActions((action) => action.resetFiltersAction) + const applyFiltersAction = ArtworksFiltersStore.useStoreActions( + (action) => action.applyFiltersAction + ) + const resetFiltersAction = ArtworksFiltersStore.useStoreActions( + (action) => action.resetFiltersAction + ) const isEnabledImprovedAlertsFlow = useFeatureFlag("AREnableImprovedAlertsFlow") const handleClosingModal = () => { @@ -147,7 +156,8 @@ export const ArtworkFilterNavigator: React.FC = (props) => { } const isApplyButtonEnabled = - selectedFiltersState.length > 0 || (previouslyAppliedFiltersState.length === 0 && appliedFiltersState.length > 0) + selectedFiltersState.length > 0 || + (previouslyAppliedFiltersState.length === 0 && appliedFiltersState.length > 0) const handleApplyPress = () => { const appliedFiltersParams = filterArtworksParams(appliedFiltersState, filterTypeState) @@ -273,17 +283,30 @@ export const ArtworkFilterNavigator: React.FC = (props) => { cardStyle: { backgroundColor: "white" }, }} > - + - + - + - + @@ -300,9 +323,18 @@ export const ArtworkFilterNavigator: React.FC = (props) => { /> - - - + + + state.appliedFilters) - const previouslyAppliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.previouslyAppliedFilters) + const previouslyAppliedFiltersState = ArtworksFiltersStore.useStoreState( + (state) => state.previouslyAppliedFilters + ) const selectedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.selectedFilters) const aggregationsState = ArtworksFiltersStore.useStoreState((state) => state.aggregations) const filterTypeState = ArtworksFiltersStore.useStoreState((state) => state.filterType) @@ -82,9 +87,10 @@ export const ArtworkFilterOptionsScreen: React.FC< }) ) - const filterOptions: FilterDisplayConfig[] = getStaticFilterOptionsByMode(mode, localFilterOptions).concat( - aggregateFilterOptions - ) + const filterOptions: FilterDisplayConfig[] = getStaticFilterOptionsByMode( + mode, + localFilterOptions + ).concat(aggregateFilterOptions) const sortedFilterOptions = filterOptions .sort(getFilterScreenSortByMode(mode, localFilterOptions)) @@ -199,7 +205,10 @@ export const getStaticFilterOptionsByMode = ( ] } - return [filterOptionToDisplayConfigMap.waysToBuy, filterOptionToDisplayConfigMap.attributionClass] + return [ + filterOptionToDisplayConfigMap.waysToBuy, + filterOptionToDisplayConfigMap.attributionClass, + ] case FilterModalMode.Custom: return customFilterOptions! @@ -316,7 +325,9 @@ export const AnimatedArtworkFilterButton: React.FC filter.paramName === FilterParamName.artistsIFollow ) - const hasArtistIDs = !!appliedFiltersState.find((filter) => filter.paramName === FilterParamName.artistIDs) + const hasArtistIDs = !!appliedFiltersState.find( + (filter) => filter.paramName === FilterParamName.artistIDs + ) if (hasArtistIDs && hasArtistsIFollow) { --selectedFiltersSum @@ -573,4 +584,10 @@ const TagAndGeneFiltersSorted: FilterScreen[] = [ "partnerIDs", ] -const AuctionResultsFiltersSorted: FilterScreen[] = ["sort", "categories", "sizes", "year", "organizations"] +const AuctionResultsFiltersSorted: FilterScreen[] = [ + "sort", + "categories", + "sizes", + "year", + "organizations", +] diff --git a/src/lib/Components/ArtworkFilter/ArtworkFilterStore.tsx b/src/lib/Components/ArtworkFilter/ArtworkFilterStore.tsx index 83eab3ae424..a45f614d43a 100644 --- a/src/lib/Components/ArtworkFilter/ArtworkFilterStore.tsx +++ b/src/lib/Components/ArtworkFilter/ArtworkFilterStore.tsx @@ -161,7 +161,9 @@ export const getArtworkFiltersModel = (): ArtworkFiltersModel => ({ // Return the list of selected options (union of selected and applied) export const useSelectedOptionsDisplay = (): FilterArray => { const selectedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.selectedFilters) - const previouslyAppliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.previouslyAppliedFilters) + const previouslyAppliedFiltersState = ArtworksFiltersStore.useStoreState( + (state) => state.previouslyAppliedFilters + ) const filterTypeState = ArtworksFiltersStore.useStoreState((state) => state.filterType) return selectedOptionsUnion({ @@ -187,7 +189,11 @@ export const DEFAULT_FILTERS: FilterArray = [ { paramName: FilterParamName.waysToBuyInquire, paramValue: false, displayText: "Inquire" }, { paramName: FilterParamName.waysToBuyMakeOffer, paramValue: false, displayText: "Make Offer" }, { paramName: FilterParamName.waysToBuyBid, paramValue: false, displayText: "Bid" }, - { paramName: FilterParamName.artistsIFollow, paramValue: false, displayText: "All Artists I Follow" }, + { + paramName: FilterParamName.artistsIFollow, + paramValue: false, + displayText: "All Artists I Follow", + }, { paramName: FilterParamName.artistIDs, paramValue: [], displayText: "All" }, { paramName: FilterParamName.viewAs, paramValue: false, displayText: "Grid" }, { paramName: FilterParamName.attributionClass, paramValue: "", displayText: "All" }, diff --git a/src/lib/Components/ArtworkFilter/ArtworkFiltersStore.tests.tsx b/src/lib/Components/ArtworkFilter/ArtworkFiltersStore.tests.tsx index 001762f63ec..8c82f7acea0 100644 --- a/src/lib/Components/ArtworkFilter/ArtworkFiltersStore.tests.tsx +++ b/src/lib/Components/ArtworkFilter/ArtworkFiltersStore.tests.tsx @@ -1,6 +1,9 @@ import { createStore } from "easy-peasy" import { FilterArray, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { getArtworkFiltersModel, selectedOptionsUnion } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + getArtworkFiltersModel, + selectedOptionsUnion, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { ArtworkFiltersModel, ArtworkFiltersState } from "./ArtworkFilterStore" let filterState: ArtworkFiltersState @@ -12,8 +15,12 @@ describe("Reset Filters", () => { it("returns empty arrays/default state values ", () => { filterState = { appliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], applyFilters: true, aggregations: [], filterType: "artwork", @@ -30,7 +37,9 @@ describe("Reset Filters", () => { appliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], applyFilters: false, selectedFilters: [], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -43,9 +52,13 @@ describe("Reset Filters", () => { it("returns empty arrays/default state values ", () => { filterState = { appliedFilters: [{ displayText: "Price (Low to High)", paramName: FilterParamName.sort }], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], applyFilters: false, - previouslyAppliedFilters: [{ displayText: "Price (Low to High)", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Price (Low to High)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -61,7 +74,9 @@ describe("Reset Filters", () => { appliedFilters: [{ displayText: "Price (Low to High)", paramName: FilterParamName.sort }], applyFilters: false, selectedFilters: [], - previouslyAppliedFilters: [{ displayText: "Price (Low to High)", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Price (Low to High)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -381,7 +396,9 @@ describe("Select Filters", () => { applyFilters: false, appliedFilters: [], previouslyAppliedFilters: [], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -433,7 +450,9 @@ describe("Select Filters", () => { applyFilters: false, appliedFilters: [], previouslyAppliedFilters: [], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -446,8 +465,12 @@ describe("Select Filters", () => { it("does not select a filter that is already applied", () => { filterState = { applyFilters: false, - appliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + appliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], + previouslyAppliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], selectedFilters: [], aggregations: [], filterType: "artwork", @@ -465,8 +488,12 @@ describe("Select Filters", () => { expect(filterArtworksStore.getState()).toEqual({ applyFilters: false, - appliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + appliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], + previouslyAppliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], selectedFilters: [], aggregations: [], filterType: "artwork", @@ -667,7 +694,9 @@ describe("Apply Filters", () => { applyFilters: true, appliedFilters: [], previouslyAppliedFilters: [], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -681,8 +710,12 @@ describe("Apply Filters", () => { expect(filterArtworksStore.getState()).toEqual({ applyFilters: true, - appliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + appliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], + previouslyAppliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], selectedFilters: [], aggregations: [], filterType: "artwork", @@ -697,7 +730,9 @@ describe("Apply Filters", () => { filterState = { applyFilters: true, appliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], selectedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], aggregations: [], filterType: "artwork", @@ -713,7 +748,9 @@ describe("Apply Filters", () => { expect(filterArtworksStore.getState()).toEqual({ applyFilters: true, appliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], selectedFilters: [], aggregations: [], filterType: "artwork", @@ -727,9 +764,15 @@ describe("Apply Filters", () => { it("applies false ways to buy filters correctly", () => { filterState = { applyFilters: false, - appliedFilters: [{ paramName: FilterParamName.waysToBuyBuy, paramValue: true, displayText: "Buy Now" }], - previouslyAppliedFilters: [{ paramName: FilterParamName.waysToBuyBuy, paramValue: true, displayText: "Buy Now" }], - selectedFilters: [{ paramName: FilterParamName.waysToBuyBuy, paramValue: false, displayText: "Buy Now" }], + appliedFilters: [ + { paramName: FilterParamName.waysToBuyBuy, paramValue: true, displayText: "Buy Now" }, + ], + previouslyAppliedFilters: [ + { paramName: FilterParamName.waysToBuyBuy, paramValue: true, displayText: "Buy Now" }, + ], + selectedFilters: [ + { paramName: FilterParamName.waysToBuyBuy, paramValue: false, displayText: "Buy Now" }, + ], aggregations: [], filterType: "artwork", counts: { total: null, followedArtists: null }, @@ -753,8 +796,12 @@ describe("Apply Filters", () => { filterState = { applyFilters: true, appliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -768,8 +815,12 @@ describe("Apply Filters", () => { expect(filterArtworksStore.getState()).toEqual({ applyFilters: true, - appliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + appliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], + previouslyAppliedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], selectedFilters: [], aggregations: [], filterType: "artwork", @@ -942,8 +993,12 @@ describe("clearFiltersZeroState", () => { { displayText: "Recently Updated", paramName: FilterParamName.sort }, { displayText: "Jewelry", paramName: FilterParamName.medium }, ], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], aggregations: [], filterType: "artwork", counts: { @@ -972,7 +1027,9 @@ describe("clearFiltersZeroState", () => { it("clears out the selectedFilters", () => { filterState = { appliedFilters: [], - selectedFilters: [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }], + selectedFilters: [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ], previouslyAppliedFilters: [], applyFilters: true, aggregations: [], @@ -1019,12 +1076,16 @@ describe("SetInitialFilterState", () => { const filterArtworksStore = getFilterArtworksStore(filterState) filterArtworksStore .getActions() - .setInitialFilterStateAction([{ displayText: "Recently Updated", paramName: FilterParamName.sort }]) + .setInitialFilterStateAction([ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ]) expect(filterArtworksStore.getState()).toEqual({ appliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], selectedFilters: [], - previouslyAppliedFilters: [{ displayText: "Recently Updated", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ], applyFilters: false, aggregations: [], filterType: "artwork", @@ -1039,8 +1100,12 @@ describe("SetInitialFilterState", () => { describe("selectedOptionsUnion", () => { describe("artworks", () => { it("correctly unions params", () => { - const previouslyAppliedFilters = [{ displayText: "Recently Updated", paramName: FilterParamName.sort }] - const selectedFilters = [{ displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }] + const previouslyAppliedFilters = [ + { displayText: "Recently Updated", paramName: FilterParamName.sort }, + ] + const selectedFilters = [ + { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, + ] expect(selectedOptionsUnion({ selectedFilters, previouslyAppliedFilters })).toEqual([ { displayText: "Artwork Year (Descending)", paramName: FilterParamName.sort }, @@ -1732,10 +1797,20 @@ describe("selectedOptionsUnion", () => { describe("saleArtworks", () => { it("correctly sets selected filter", () => { - const previouslyAppliedFilters = [{ displayText: "Lot Number Ascending", paramName: FilterParamName.sort }] - const selectedFilters = [{ displayText: "Lot Number Descending", paramName: FilterParamName.sort }] + const previouslyAppliedFilters = [ + { displayText: "Lot Number Ascending", paramName: FilterParamName.sort }, + ] + const selectedFilters = [ + { displayText: "Lot Number Descending", paramName: FilterParamName.sort }, + ] - expect(selectedOptionsUnion({ selectedFilters, previouslyAppliedFilters, filterType: "saleArtwork" })).toEqual([ + expect( + selectedOptionsUnion({ + selectedFilters, + previouslyAppliedFilters, + filterType: "saleArtwork", + }) + ).toEqual([ { displayText: "Lot Number Descending", paramName: FilterParamName.sort }, { displayText: "All", @@ -1844,7 +1919,13 @@ describe("selectedOptionsUnion", () => { }, ] - expect(selectedOptionsUnion({ selectedFilters, previouslyAppliedFilters, filterType: "saleArtwork" })).toEqual([ + expect( + selectedOptionsUnion({ + selectedFilters, + previouslyAppliedFilters, + filterType: "saleArtwork", + }) + ).toEqual([ { paramName: FilterParamName.artistIDs, paramValue: ["artist-1"], @@ -1963,7 +2044,13 @@ describe("selectedOptionsUnion", () => { }, ] - expect(selectedOptionsUnion({ selectedFilters, previouslyAppliedFilters, filterType: "saleArtwork" })).toEqual([ + expect( + selectedOptionsUnion({ + selectedFilters, + previouslyAppliedFilters, + filterType: "saleArtwork", + }) + ).toEqual([ { displayText: "All", paramName: "artistIDs", @@ -2072,8 +2159,18 @@ describe("selectedOptionsUnion", () => { const previouslyAppliedFilters = [] as FilterArray const selectedFilters = [] as FilterArray - expect(selectedOptionsUnion({ selectedFilters, previouslyAppliedFilters, filterType: "showArtwork" })).toEqual([ - { displayText: "Gallery Curated", paramName: FilterParamName.sort, paramValue: "partner_show_position" }, + expect( + selectedOptionsUnion({ + selectedFilters, + previouslyAppliedFilters, + filterType: "showArtwork", + }) + ).toEqual([ + { + displayText: "Gallery Curated", + paramName: FilterParamName.sort, + paramValue: "partner_show_position", + }, { displayText: "All", paramName: "estimateRange", diff --git a/src/lib/Components/ArtworkFilter/FilterArtworksHelpers.tests.tsx b/src/lib/Components/ArtworkFilter/FilterArtworksHelpers.tests.tsx index a4cea18e0ed..294c0b910a7 100644 --- a/src/lib/Components/ArtworkFilter/FilterArtworksHelpers.tests.tsx +++ b/src/lib/Components/ArtworkFilter/FilterArtworksHelpers.tests.tsx @@ -1,4 +1,7 @@ -import { FilterArray, getUnitedSelectedAndAppliedFilters } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterArray, + getUnitedSelectedAndAppliedFilters, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { aggregationsWithFollowedArtists, changedFiltersParams, diff --git a/src/lib/Components/ArtworkFilter/FilterModal.tests.tsx b/src/lib/Components/ArtworkFilter/FilterModal.tests.tsx index 55a8146c91c..95d6764f396 100644 --- a/src/lib/Components/ArtworkFilter/FilterModal.tests.tsx +++ b/src/lib/Components/ArtworkFilter/FilterModal.tests.tsx @@ -7,7 +7,10 @@ import { FilterModalMode, } from "lib/Components/ArtworkFilter" import { Aggregations, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { CollectionFixture } from "lib/Scenes/Collection/Components/__fixtures__/CollectionFixture" import { CollectionArtworksFragmentContainer } from "lib/Scenes/Collection/Screens/CollectionArtworks" import { __globalStoreTestUtils__, GlobalStoreProvider } from "lib/store/GlobalStore" @@ -18,7 +21,12 @@ import React from "react" import { graphql, QueryRenderer } from "react-relay" import { useTracking } from "react-tracking" import { createMockEnvironment } from "relay-test-utils" -import { closeModalMock, getEssentialProps, MockFilterScreen, navigateMock } from "./FilterTestHelper" +import { + closeModalMock, + getEssentialProps, + MockFilterScreen, + navigateMock, +} from "./FilterTestHelper" const exitModalMock = jest.fn() const trackEvent = jest.fn() @@ -282,7 +290,9 @@ describe("Filter modal states", () => { }, } - const { getAllByText } = renderWithWrappersTL() + const { getAllByText } = renderWithWrappersTL( + + ) expect(getAllByText("Show results")[0]).not.toBeDisabled() }) @@ -298,7 +308,11 @@ describe("Filter modal states", () => { it("displays selected filters on the Filter modal", () => { const injectedState: ArtworkFiltersState = { selectedFilters: [ - { displayText: "Drawing", paramValue: ["drawing"], paramName: FilterParamName.additionalGeneIDs }, + { + displayText: "Drawing", + paramValue: ["drawing"], + paramName: FilterParamName.additionalGeneIDs, + }, { displayText: "Price (Low to High)", paramName: FilterParamName.sort }, { displayText: "$10,000-20,000", paramName: FilterParamName.priceRange }, { @@ -306,7 +320,11 @@ describe("Filter modal states", () => { paramValue: true, paramName: FilterParamName.waysToBuyBid, }, - { displayText: "All", paramValue: ["2020-Today", "1970-1979"], paramName: FilterParamName.timePeriod }, + { + displayText: "All", + paramValue: ["2020-Today", "1970-1979"], + paramName: FilterParamName.timePeriod, + }, ], appliedFilters: [], previouslyAppliedFilters: [], @@ -341,7 +359,9 @@ describe("Clearing filters", () => { }, ], appliedFilters: [{ displayText: "Recently Added", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Recently Added", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Added", paramName: FilterParamName.sort }, + ], applyFilters: false, aggregations: mockAggregations, filterType: "artwork", @@ -364,7 +384,9 @@ describe("Clearing filters", () => { const injectedState: ArtworkFiltersState = { selectedFilters: [], appliedFilters: [{ displayText: "Recently Added", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Recently Added", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Recently Added", paramName: FilterParamName.sort }, + ], applyFilters: false, aggregations: mockAggregations, filterType: "artwork", @@ -374,7 +396,9 @@ describe("Clearing filters", () => { }, } - const { getAllByText, getByText } = renderWithWrappersTL() + const { getAllByText, getByText } = renderWithWrappersTL( + + ) expect(getAllByText("Show results")[0]).toBeDisabled() @@ -410,7 +434,10 @@ describe("Applying filters on Artworks", () => { - + @@ -426,7 +453,9 @@ describe("Applying filters on Artworks", () => { const injectedState: ArtworkFiltersState = { selectedFilters: [{ displayText: "Price (High to Low)", paramName: FilterParamName.sort }], appliedFilters: [{ displayText: "Price (High to Low)", paramName: FilterParamName.sort }], - previouslyAppliedFilters: [{ displayText: "Price (High to Low)", paramName: FilterParamName.sort }], + previouslyAppliedFilters: [ + { displayText: "Price (High to Low)", paramName: FilterParamName.sort }, + ], applyFilters: true, aggregations: mockAggregations, filterType: "artwork", @@ -471,13 +500,25 @@ describe("Applying filters on Artworks", () => { it.skip("tracks changes in the filter state when a filter is applied", async () => { const injectedState: ArtworkFiltersState = { selectedFilters: [ - { displayText: "Works on Paper", paramName: FilterParamName.medium, paramValue: "work-on-paper" }, + { + displayText: "Works on Paper", + paramName: FilterParamName.medium, + paramValue: "work-on-paper", + }, ], appliedFilters: [ - { displayText: "Recently Added", paramName: FilterParamName.sort, paramValue: "-decayed_merch" }, + { + displayText: "Recently Added", + paramName: FilterParamName.sort, + paramValue: "-decayed_merch", + }, ], previouslyAppliedFilters: [ - { displayText: "Recently Added", paramName: FilterParamName.sort, paramValue: "-decayed_merch" }, + { + displayText: "Recently Added", + paramName: FilterParamName.sort, + paramValue: "-decayed_merch", + }, ], applyFilters: true, aggregations: mockAggregations, @@ -488,7 +529,9 @@ describe("Applying filters on Artworks", () => { }, } - const { getAllByText } = renderWithWrappersTL() + const { getAllByText } = renderWithWrappersTL( + + ) mockEnvironmentPayload(env) @@ -552,7 +595,9 @@ describe("Saved Search Flow", () => { }) it('should show "Create Alert" button when shouldShowCreateAlertButton prop is passed', () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("Create Alert")).toBeTruthy() }) diff --git a/src/lib/Components/ArtworkFilter/FilterTestHelper.tsx b/src/lib/Components/ArtworkFilter/FilterTestHelper.tsx index 890a2bfb516..3780fb5f6ff 100644 --- a/src/lib/Components/ArtworkFilter/FilterTestHelper.tsx +++ b/src/lib/Components/ArtworkFilter/FilterTestHelper.tsx @@ -1,5 +1,9 @@ import { StackScreenProps } from "@react-navigation/stack" -import { ArtworkFilterNavigationStack, ArtworkFilterOptionsScreen, FilterModalMode } from "lib/Components/ArtworkFilter" +import { + ArtworkFilterNavigationStack, + ArtworkFilterOptionsScreen, + FilterModalMode, +} from "lib/Components/ArtworkFilter" import { ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { ArtworkFiltersState } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { GlobalStoreProvider } from "lib/store/GlobalStore" diff --git a/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tests.tsx index 22eeb87d739..d357d726327 100644 --- a/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tests.tsx @@ -1,6 +1,9 @@ import { fireEvent } from "@testing-library/react-native" import { Aggregations, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { MockFilterScreen } from "lib/Components/ArtworkFilter/FilterTestHelper" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import React from "react" @@ -50,7 +53,9 @@ describe("AdditionalGeneIDsOptions Screen", () => { } it("renders the options", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("Prints")).toBeTruthy() expect(getByText("Design")).toBeTruthy() diff --git a/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tsx index fb4176a13b9..cebad125624 100644 --- a/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/AdditionalGeneIDsOptions.tsx @@ -1,7 +1,11 @@ import { toTitleCase } from "@artsy/to-title-case" import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { useArtworkFiltersAggregation } from "lib/Components/ArtworkFilter/useArtworkFilters" import React from "react" import { ArtworksFiltersStore } from "../ArtworkFilterStore" @@ -11,7 +15,9 @@ import { useMultiSelect } from "./useMultiSelect" interface AdditionalGeneIDsOptionsScreenProps extends StackScreenProps {} -export const AdditionalGeneIDsOptionsScreen: React.FC = ({ navigation }) => { +export const AdditionalGeneIDsOptionsScreen: React.FC = ({ + navigation, +}) => { const filterType = ArtworksFiltersStore.useStoreState((state) => state.filterType) const localFilterOptions = ArtworksFiltersStore.useStoreState((state) => state.filterOptions) @@ -24,7 +30,11 @@ export const AdditionalGeneIDsOptionsScreen: React.FC { - return { paramName: FilterParamName.additionalGeneIDs, displayText: toTitleCase(displayText), paramValue } + return { + paramName: FilterParamName.additionalGeneIDs, + displayText: toTitleCase(displayText), + paramValue, + } }) } diff --git a/src/lib/Components/ArtworkFilter/Filters/AggregationOptionCommonValidation.tsx b/src/lib/Components/ArtworkFilter/Filters/AggregationOptionCommonValidation.tsx index 10f506cc776..f9b3e12dc5a 100644 --- a/src/lib/Components/ArtworkFilter/Filters/AggregationOptionCommonValidation.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/AggregationOptionCommonValidation.tsx @@ -1,5 +1,12 @@ -import { aggregationForFilter, Aggregations, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + aggregationForFilter, + Aggregations, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { TouchableRow } from "lib/Components/TouchableRow" import { extractText } from "lib/tests/extractText" import { renderWithWrappers } from "lib/tests/renderWithWrappers" @@ -22,7 +29,9 @@ export interface ValidationParams { export const sharedAggregateFilterValidation = (params: ValidationParams) => { const selectedFilterOption = (componentTree: ReactTestRenderer) => { const innerOptions = componentTree.root.findAllByType(InnerOptionListItem) - const selectedOption = innerOptions.filter((item) => item.findByType(RadioDot).props.selected)[0] + const selectedOption = innerOptions.filter( + (item) => item.findByType(RadioDot).props.selected + )[0] return selectedOption } @@ -42,7 +51,11 @@ export const sharedAggregateFilterValidation = (params: ValidationParams) => { }, } - const MockScreenWrapper = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => ( + const MockScreenWrapper = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => ( @@ -104,8 +117,11 @@ export const sharedAggregateFilterValidation = (params: ValidationParams) => { () => { const tree = renderWithWrappers() - const [firstOptionInstance, secondOptionInstance, thirdOptionInstance] = tree.root.findAllByType(TouchableRow) - const selectedOptionIconBeforePress = tree.root.findAllByType(RadioDot).filter((item) => item.props.selected) + const [firstOptionInstance, secondOptionInstance, thirdOptionInstance] = + tree.root.findAllByType(TouchableRow) + const selectedOptionIconBeforePress = tree.root + .findAllByType(RadioDot) + .filter((item) => item.props.selected) expect(selectedOptionIconBeforePress).toHaveLength(1) @@ -113,7 +129,9 @@ export const sharedAggregateFilterValidation = (params: ValidationParams) => { act(() => secondOptionInstance.props.onPress()) act(() => thirdOptionInstance.props.onPress()) - const selectedOptionIconAfterPress = tree.root.findAllByType(RadioDot).filter((item) => item.props.selected) + const selectedOptionIconAfterPress = tree.root + .findAllByType(RadioDot) + .filter((item) => item.props.selected) expect(selectedOptionIconAfterPress).toHaveLength(1) } diff --git a/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tests.tsx index f11e6752090..aaf7f9b23ed 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tests.tsx @@ -1,6 +1,9 @@ import { fireEvent } from "@testing-library/react-native" import { Aggregations, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import React from "react" import { ArtistIDsArtworksOptionsScreen } from "./ArtistIDsArtworksOptions" @@ -71,7 +74,9 @@ describe("Artist options screen", () => { followedArtists: null, }, } - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) expect(getAllByA11yState({ checked: false })).toHaveLength(6) }) @@ -97,7 +102,9 @@ describe("Artist options screen", () => { }, } - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const selectedOptions = getAllByA11yState({ checked: true }) expect(selectedOptions[0]).toHaveTextContent("Artist 2") @@ -117,7 +124,9 @@ describe("Artist options screen", () => { }, } - const { getByText, getAllByA11yState } = renderWithWrappersTL() + const { getByText, getAllByA11yState } = renderWithWrappersTL( + + ) fireEvent.press(getByText("All Artists I Follow")) fireEvent.press(getByText("Artist 1")) diff --git a/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tsx index 4b2164ae8a0..b802609af40 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ArtistIDsArtworksOptions.tsx @@ -6,7 +6,10 @@ import { FilterDisplayName, FilterParamName, } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" import { sortBy } from "lodash" @@ -17,10 +20,14 @@ import { useMultiSelect } from "./useMultiSelect" interface ArtistIDsArtworksOptionsScreenProps extends StackScreenProps {} -export const ArtistIDsArtworksOptionsScreen: React.FC = ({ navigation }) => { +export const ArtistIDsArtworksOptionsScreen: React.FC = ({ + navigation, +}) => { const selectedOptions = useSelectedOptionsDisplay() const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations) - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const counts = ArtworksFiltersStore.useStoreState((state) => state.counts) const filterType = ArtworksFiltersStore.useStoreState((state) => state.filterType) const localFilterOptions = ArtworksFiltersStore.useStoreState((state) => state.filterOptions) @@ -31,7 +38,8 @@ export const ArtistIDsArtworksOptionsScreen: React.FC o.filterType === "artistIDs")!.values! + artistDisplayOptions = (localFilterOptions ?? []).find((o) => o.filterType === "artistIDs")! + .values! } else { const aggregation = aggregationForFilter(FilterParamName.artistIDs, aggregations) artistDisplayOptions = @@ -50,7 +58,10 @@ export const ArtistIDsArtworksOptionsScreen: React.FC ({ ...option, paramValue: isSelected(option) })) + const formattedArtistOptions = artistDisplayOptions.map((option) => ({ + ...option, + paramValue: isSelected(option), + })) const sortedArtistOptions = sortBy(formattedArtistOptions, ["displayText"]) // If FOLLOWED_ARTISTS is included in the list of available aggregations, it means diff --git a/src/lib/Components/ArtworkFilter/Filters/ArtistIDsSaleArtworksOptionsScreen.tsx b/src/lib/Components/ArtworkFilter/Filters/ArtistIDsSaleArtworksOptionsScreen.tsx index 213712053b5..4a463c849dc 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ArtistIDsSaleArtworksOptionsScreen.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ArtistIDsSaleArtworksOptionsScreen.tsx @@ -6,7 +6,10 @@ import { FilterDisplayName, FilterParamName, } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import React from "react" import { MultiSelectCheckOptionScreen } from "./MultiSelectCheckOption" import { useMultiSelect } from "./useMultiSelect" @@ -21,11 +24,13 @@ const isAllArtistsFilter = (option: FilterData) => { return option.displayText === "All Artists" } -export const ArtistIDsSaleArtworksOptionsScreen: React.FC = ({ - navigation, -}) => { +export const ArtistIDsSaleArtworksOptionsScreen: React.FC< + ArtistIDsSaleArtworksOptionsScreenProps +> = ({ navigation }) => { const paramName = FilterParamName.artistIDs - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const counts = ArtworksFiltersStore.useStoreState((state) => state.counts) const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations) const aggregation = aggregationForFilter(paramName, aggregations) diff --git a/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tests.tsx index a6e86d69873..8beb5b3ae58 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tests.tsx @@ -1,5 +1,8 @@ import { Aggregations, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { RightButtonContainer } from "lib/Components/FancyModal/FancyModalHeader" import { extractText } from "lib/tests/extractText" import { renderWithWrappers } from "lib/tests/renderWithWrappers" @@ -49,7 +52,9 @@ describe("ArtistNationalitiesOptionsScreen", () => { } it("renders the options", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(tree.root.findAllByType(OptionListItem)).toHaveLength(5) const items = tree.root.findAllByType(OptionListItem) expect(items.map(extractText)).toEqual(["American", "British", "German", "Italian", "Japanese"]) @@ -67,7 +72,9 @@ describe("ArtistNationalitiesOptionsScreen", () => { ], } - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const options = tree.root.findAllByType(Check) expect(options[0].props.selected).toBe(true) @@ -89,7 +96,9 @@ describe("ArtistNationalitiesOptionsScreen", () => { ], } - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const options = tree.root.findAllByType(Check) const clear = tree.root.findByType(RightButtonContainer) diff --git a/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx index 7906b2fa7d2..e7730dfef98 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx @@ -12,7 +12,9 @@ const PARAM_NAME = FilterParamName.artistNationalities interface ArtistNationalitiesOptionsScreenProps extends StackScreenProps {} -export const ArtistNationalitiesOptionsScreen: React.FC = ({ navigation }) => { +export const ArtistNationalitiesOptionsScreen: React.FC = ({ + navigation, +}) => { const { aggregation } = useArtworkFiltersAggregation({ paramName: PARAM_NAME }) const options: FilterData[] = (aggregation?.counts ?? []).map(({ value: paramValue, name }) => { diff --git a/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tests.tsx index e30013343ab..d08d154c4ac 100644 --- a/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tests.tsx @@ -1,5 +1,8 @@ import { FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { MockFilterScreen } from "lib/Components/ArtworkFilter/FilterTestHelper" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import React from "react" @@ -7,7 +10,11 @@ import { AttributionClassOptionsScreen } from "./AttributionClassOptions" import { getEssentialProps } from "./helper" describe("AttributionClassOptions Screen", () => { - const MockAttributionClassOptionsScreen = ({ initialData }: { initialData?: ArtworkFiltersState }) => { + const MockAttributionClassOptionsScreen = ({ + initialData, + }: { + initialData?: ArtworkFiltersState + }) => { return ( diff --git a/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tsx index 158603474a7..d88162fbe0d 100644 --- a/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/AttributionClassOptions.tsx @@ -1,6 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import React from "react" import { MultiSelectOptionScreen } from "./MultiSelectOption" import { useMultiSelect } from "./useMultiSelect" @@ -10,18 +14,35 @@ interface AttributionClassOptionsScreenProps export const ATTRIBUTION_CLASS_OPTIONS: FilterData[] = [ { displayText: "Unique", paramValue: "unique", paramName: FilterParamName.attributionClass }, - { displayText: "Limited Edition", paramValue: "limited edition", paramName: FilterParamName.attributionClass }, - { displayText: "Open Edition", paramValue: "open edition", paramName: FilterParamName.attributionClass }, - { displayText: "Unknown Edition", paramValue: "unknown edition", paramName: FilterParamName.attributionClass }, + { + displayText: "Limited Edition", + paramValue: "limited edition", + paramName: FilterParamName.attributionClass, + }, + { + displayText: "Open Edition", + paramValue: "open edition", + paramName: FilterParamName.attributionClass, + }, + { + displayText: "Unknown Edition", + paramValue: "unknown edition", + paramName: FilterParamName.attributionClass, + }, ] -export const AttributionClassOptionsScreen: React.FC = ({ navigation }) => { +export const AttributionClassOptionsScreen: React.FC = ({ + navigation, +}) => { const { handleSelect, isSelected, handleClear, isActive } = useMultiSelect({ options: ATTRIBUTION_CLASS_OPTIONS, paramName: FilterParamName.attributionClass, }) - const filterOptions = ATTRIBUTION_CLASS_OPTIONS.map((option) => ({ ...option, paramValue: isSelected(option) })) + const filterOptions = ATTRIBUTION_CLASS_OPTIONS.map((option) => ({ + ...option, + paramValue: isSelected(option), + })) return ( { - const MockAuctionHouseScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { + const MockAuctionHouseScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => { return ( diff --git a/src/lib/Components/ArtworkFilter/Filters/AuctionHouseOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/AuctionHouseOptions.tsx index c74b3b59ef0..e4b14865367 100644 --- a/src/lib/Components/ArtworkFilter/Filters/AuctionHouseOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/AuctionHouseOptions.tsx @@ -1,6 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import React from "react" import { MultiSelectOptionScreen } from "./MultiSelectOption" import { useMultiSelect } from "./useMultiSelect" @@ -26,13 +30,18 @@ export const AUCTION_HOUSE_OPTIONS: FilterData[] = [ interface AuctionHouseOptionsScreenProps extends StackScreenProps {} -export const AuctionHouseOptionsScreen: React.FC = ({ navigation }) => { +export const AuctionHouseOptionsScreen: React.FC = ({ + navigation, +}) => { const { handleSelect, isSelected, handleClear, isActive } = useMultiSelect({ options: AUCTION_HOUSE_OPTIONS, paramName: FilterParamName.organizations, }) - const filterOptions = AUCTION_HOUSE_OPTIONS.map((option) => ({ ...option, paramValue: isSelected(option) })) + const filterOptions = AUCTION_HOUSE_OPTIONS.map((option) => ({ + ...option, + paramValue: isSelected(option), + })) return ( { - const MockCategoryScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { + const MockCategoryScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => { return ( diff --git a/src/lib/Components/ArtworkFilter/Filters/CategoriesOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/CategoriesOptions.tsx index b253d420e05..0cfc23ba3b1 100644 --- a/src/lib/Components/ArtworkFilter/Filters/CategoriesOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/CategoriesOptions.tsx @@ -1,6 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import React from "react" import { MultiSelectOptionScreen } from "./MultiSelectOption" import { useMultiSelect } from "./useMultiSelect" @@ -41,13 +45,18 @@ export const CATEGORIES_OPTIONS: FilterData[] = [ }, ] -export const CategoriesOptionsScreen: React.FC = ({ navigation }) => { +export const CategoriesOptionsScreen: React.FC = ({ + navigation, +}) => { const { handleSelect, isSelected, handleClear, isActive } = useMultiSelect({ options: CATEGORIES_OPTIONS, paramName: FilterParamName.categories, }) - const filterOptions = CATEGORIES_OPTIONS.map((option) => ({ ...option, paramValue: isSelected(option) })) + const filterOptions = CATEGORIES_OPTIONS.map((option) => ({ + ...option, + paramValue: isSelected(option), + })) return ( { return selectedOption } - const MockColorScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { + const MockColorScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => { return ( @@ -72,7 +83,11 @@ describe("Colors options screen", () => { it("shows the correct number of color options", () => { const tree = renderWithWrappers( - + ) expect(tree.root.findAllByType(ColorsSwatch)).toHaveLength(aggregation!.counts.length) @@ -99,7 +114,9 @@ describe("Colors options screen", () => { }, } - const component = renderWithWrappers() + const component = renderWithWrappers( + + ) const selectedOption = selectedColorOptions(component)[0] expect(selectedOption.props.name).toMatch(aggregation!.counts[0].name) @@ -125,7 +142,9 @@ describe("Colors options screen", () => { }, } - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const firstOptionInstance = tree.root.findAllByType(ColorsSwatch)[0] const secondOptionInstance = tree.root.findAllByType(ColorsSwatch)[1] @@ -158,7 +177,9 @@ describe("Colors options screen", () => { }, } - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const secondOptionInstance = tree.root.findAllByType(ColorsSwatch)[1] diff --git a/src/lib/Components/ArtworkFilter/Filters/ColorsOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/ColorsOptions.tsx index 26b50e16bdb..0b6ba9acac1 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ColorsOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ColorsOptions.tsx @@ -1,6 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { ArtworkFilterBackHeader } from "lib/Components/ArtworkFilter/components/ArtworkFilterBackHeader" import { useArtworkFiltersAggregation } from "lib/Components/ArtworkFilter/useArtworkFilters" import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader" @@ -13,7 +17,12 @@ import { ColorsSwatch } from "./ColorsSwatch" import { useMultiSelect } from "./useMultiSelect" export const COLORS = [ - { value: "black-and-white", name: "Black and White", backgroundColor: "#000", foregroundColor: "#fff" }, + { + value: "black-and-white", + name: "Black and White", + backgroundColor: "#000", + foregroundColor: "#fff", + }, { value: "red", name: "Red", backgroundColor: "#FF0000", foregroundColor: "#fff" }, { value: "yellow", name: "Yellow", backgroundColor: "#FBE854", foregroundColor: "#000" }, { value: "pink", name: "Pink", backgroundColor: "#FB81CD", foregroundColor: "#000" }, @@ -37,7 +46,8 @@ export const COLORS_INDEXED_BY_VALUE = COLORS.reduce( const SWATCHES_PER_ROW = 4 -interface ColorsOptionsScreenProps extends StackScreenProps {} +interface ColorsOptionsScreenProps + extends StackScreenProps {} export const ColorsOptionsScreen: React.FC = ({ navigation }) => { const space = useSpace() diff --git a/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tests.tsx index b782a0c898a..3274c99aba2 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tests.tsx @@ -6,13 +6,25 @@ import { ColorsSwatch } from "./ColorsSwatch" describe("Colors swatch", () => { it("adds a check icon when selected", () => { const selectedTree = renderWithWrappers( - + ) const selectedCheckIcon = selectedTree.root.findByType(CheckIcon) expect(selectedCheckIcon.props.fill).toMatch("#fff") const unselectedTree = renderWithWrappers( - + ) const unselectedCheckIcon = unselectedTree.root.findAllByType(CheckIcon) expect(unselectedCheckIcon.length).toEqual(0) @@ -20,7 +32,13 @@ describe("Colors swatch", () => { it("has correct background color for passed in color", () => { const darkblue = renderWithWrappers( - + ) const darkBlueView = darkblue.root.findAllByType(Box)[1] expect(darkBlueView.props.bg).toMatch("#435EA9") @@ -39,7 +57,13 @@ describe("Colors swatch", () => { expect(blackAndWhiteView.props.bg).toMatch("#595A5B") const orange = renderWithWrappers( - + ) const orangeView = orange.root.findAllByType(Box)[1] expect(orangeView.props.bg).toMatch("#F1572C") diff --git a/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tsx b/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tsx index 80d863ccbdb..cdfc9634933 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ColorsSwatch.tsx @@ -21,7 +21,14 @@ export const ColorsSwatch: React.FC = ({ return ( - + {!!selected && ( { const TestRenderer = (props: Partial) => { - return + return ( + + ) } it("renders without throwing an error", () => { diff --git a/src/lib/Components/ArtworkFilter/Filters/CustomSizeInputs.tsx b/src/lib/Components/ArtworkFilter/Filters/CustomSizeInputs.tsx index 4fe0e3ba1af..669c147acc9 100644 --- a/src/lib/Components/ArtworkFilter/Filters/CustomSizeInputs.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/CustomSizeInputs.tsx @@ -19,7 +19,12 @@ const getValue = (value: Numeric) => { return value.toString() } -export const CustomSizeInputs: React.FC = ({ label, range, active, onChange }) => { +export const CustomSizeInputs: React.FC = ({ + label, + range, + active, + onChange, +}) => { const color = useColor() const handleInputChange = (field: keyof Range) => (text: string) => { const parsed = parseFloat(text) diff --git a/src/lib/Components/ArtworkFilter/Filters/EstimateRangeOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/EstimateRangeOptions.tsx index f7cdfb3b352..c15422860fe 100644 --- a/src/lib/Components/ArtworkFilter/Filters/EstimateRangeOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/EstimateRangeOptions.tsx @@ -1,7 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" import { AggregateOption, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { Sans, Separator } from "palette" import React from "react" import { SingleSelectOptionScreen } from "./SingleSelectOption" @@ -18,10 +21,14 @@ const EstimateRanges = [ { paramValue: "5000000-*", paramDisplay: "$50,000+" }, ] -export const EstimateRangeOptionsScreen: React.FC = ({ navigation }) => { +export const EstimateRangeOptionsScreen: React.FC = ({ + navigation, +}) => { const paramName = FilterParamName.estimateRange - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const options = EstimateRanges.map((estimateRange) => { return { diff --git a/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tests.tsx index 7da5db638ed..29cf43c5db7 100644 --- a/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tests.tsx @@ -55,7 +55,9 @@ describe("Galleries and Institutions Options Screen", () => { describe("before any filters are selected", () => { it("renders all options present in the aggregation", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("Musée Picasso Paris")) expect(getByText("Gagosian")) @@ -82,7 +84,9 @@ describe("Galleries and Institutions Options Screen", () => { }) it("toggles selected filters 'ON' and unselected filters 'OFF", async () => { - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const options = getAllByA11yState({ checked: true }) diff --git a/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tsx index 4356ef8177e..73cf98b50ef 100644 --- a/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/GalleriesAndInstitutionsOptions.tsx @@ -1,6 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import React from "react" import { useArtworkFiltersAggregation } from "../useArtworkFilters" import { MultiSelectOptionScreen } from "./MultiSelectOption" @@ -9,9 +13,9 @@ import { useMultiSelect } from "./useMultiSelect" interface GalleriesAndInstitutionsOptionsScreenProps extends StackScreenProps {} -export const GalleriesAndInstitutionsOptionsScreen: React.FC = ({ - navigation, -}) => { +export const GalleriesAndInstitutionsOptionsScreen: React.FC< + GalleriesAndInstitutionsOptionsScreenProps +> = ({ navigation }) => { const { aggregation } = useArtworkFiltersAggregation({ paramName: FilterParamName.partnerIDs }) const options: FilterData[] = (aggregation?.counts ?? []).map(({ value: paramValue, name }) => { diff --git a/src/lib/Components/ArtworkFilter/Filters/KeywordFilter.tsx b/src/lib/Components/ArtworkFilter/Filters/KeywordFilter.tsx index 1cddd124cd3..cd9595753e2 100644 --- a/src/lib/Components/ArtworkFilter/Filters/KeywordFilter.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/KeywordFilter.tsx @@ -1,5 +1,8 @@ import { ActionType, ContextModule } from "@artsy/cohesion" -import { filterArtworksParams, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + filterArtworksParams, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { ArtworksFiltersStore } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import SearchIcon from "lib/Icons/SearchIcon" import { OwnerEntityTypes, PageNames } from "lib/utils/track/schema" @@ -29,8 +32,12 @@ export const KeywordFilter: React.FC = ({ const { trackEvent } = useTracking() const appliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) - const applyFiltersAction = ArtworksFiltersStore.useStoreActions((action) => action.applyFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) + const applyFiltersAction = ArtworksFiltersStore.useStoreActions( + (action) => action.applyFiltersAction + ) const appliedFiltersParams = filterArtworksParams(appliedFiltersState, "auctionResult") const inputRef = useRef(null) @@ -47,12 +54,20 @@ export const KeywordFilter: React.FC = ({ applyFiltersAction() } - const handleChangeText = useMemo(() => debounce(updateKeywordFilter, DEBOUNCE_DELAY), [appliedFiltersParams]) - const handleTypingStart = useMemo(() => throttle(() => onTypingStart?.(), DEBOUNCE_DELAY), [onTypingStart]) + const handleChangeText = useMemo( + () => debounce(updateKeywordFilter, DEBOUNCE_DELAY), + [appliedFiltersParams] + ) + const handleTypingStart = useMemo( + () => throttle(() => onTypingStart?.(), DEBOUNCE_DELAY), + [onTypingStart] + ) // clear input text when keyword filter is reseted useEffect(() => { - const appliedKeywordFilter = appliedFiltersState?.find((filter) => filter.paramName === FilterParamName.keyword) + const appliedKeywordFilter = appliedFiltersState?.find( + (filter) => filter.paramName === FilterParamName.keyword + ) if (appliedKeywordFilter?.paramValue || !inputRef.current) { return @@ -91,7 +106,12 @@ export const KeywordFilter: React.FC = ({ } const tracks = { - changeKeywordFilter: (appliedFiltersParams: any, text: string, artistId: string, artistSlug: string) => { + changeKeywordFilter: ( + appliedFiltersParams: any, + text: string, + artistId: string, + artistSlug: string + ) => { return { context_module: ContextModule.auctionResults, context_screen: PageNames.ArtistPage, diff --git a/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tests.tsx index e7ee4d43eeb..ba250aa6949 100644 --- a/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tests.tsx @@ -41,7 +41,11 @@ describe(LocationCitiesOptionsScreen, () => { selectedFilters: [], } - const MockLocationCitiesOptionsScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { + const MockLocationCitiesOptionsScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => { return ( @@ -51,7 +55,9 @@ describe(LocationCitiesOptionsScreen, () => { describe("no filters are selected", () => { it("renders all options present in the aggregation", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("Paris, France")).toBeTruthy() expect(getByText("London, United Kingdom")).toBeTruthy() @@ -78,7 +84,9 @@ describe(LocationCitiesOptionsScreen, () => { }) it("toggles selected filters 'ON' and unselected filters 'OFF", async () => { - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const options = getAllByA11yState({ checked: true }) diff --git a/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tsx index 1ad2d8d2ff5..1d8f468e9ad 100644 --- a/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/LocationCitiesOptions.tsx @@ -1,6 +1,10 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import React from "react" import { useArtworkFiltersAggregation } from "../useArtworkFilters" import { MultiSelectOptionScreen } from "./MultiSelectOption" @@ -9,8 +13,12 @@ import { useMultiSelect } from "./useMultiSelect" interface LocationCitiesOptionsScreenProps extends StackScreenProps {} -export const LocationCitiesOptionsScreen: React.FC = ({ navigation }) => { - const { aggregation } = useArtworkFiltersAggregation({ paramName: FilterParamName.locationCities }) +export const LocationCitiesOptionsScreen: React.FC = ({ + navigation, +}) => { + const { aggregation } = useArtworkFiltersAggregation({ + paramName: FilterParamName.locationCities, + }) const options: FilterData[] = (aggregation?.counts ?? []).map(({ value: paramValue, name }) => { return { displayText: name, paramName: FilterParamName.locationCities, paramValue } diff --git a/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tests.tsx index c22ef8fb693..43e2ca6e354 100644 --- a/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tests.tsx @@ -41,7 +41,11 @@ describe("Materials Options Screen", () => { selectedFilters: [], } - const MockMaterialsTermsOptionsScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { + const MockMaterialsTermsOptionsScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => { return ( @@ -51,7 +55,9 @@ describe("Materials Options Screen", () => { describe("before any filters are selected", () => { it("renders all options present in the aggregation", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("Acrylic")).toBeTruthy() expect(getByText("Canvas")).toBeTruthy() @@ -78,7 +84,9 @@ describe("Materials Options Screen", () => { }) it("toggles selected filters 'ON' and unselected filters 'OFF", async () => { - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const options = getAllByA11yState({ checked: true }) expect(options).toHaveLength(1) diff --git a/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tsx index d52a7f2fcc1..0706d0cc903 100644 --- a/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/MaterialsTermsOptions.tsx @@ -1,6 +1,10 @@ import { toTitleCase } from "@artsy/to-title-case" import { StackScreenProps } from "@react-navigation/stack" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { useArtworkFiltersAggregation } from "lib/Components/ArtworkFilter/useArtworkFilters" import { orderBy } from "lodash" import React from "react" @@ -11,13 +15,24 @@ import { useMultiSelect } from "./useMultiSelect" interface MaterialsTermsOptionsScreenProps extends StackScreenProps {} -export const MaterialsTermsOptionsScreen: React.FC = ({ navigation }) => { - const { aggregation } = useArtworkFiltersAggregation({ paramName: FilterParamName.materialsTerms }) - - const options: FilterData[] = (aggregation?.counts ?? []).map(({ value: paramValue, name, count }) => { - return { displayText: toTitleCase(name), paramName: FilterParamName.materialsTerms, paramValue, count } +export const MaterialsTermsOptionsScreen: React.FC = ({ + navigation, +}) => { + const { aggregation } = useArtworkFiltersAggregation({ + paramName: FilterParamName.materialsTerms, }) + const options: FilterData[] = (aggregation?.counts ?? []).map( + ({ value: paramValue, name, count }) => { + return { + displayText: toTitleCase(name), + paramName: FilterParamName.materialsTerms, + paramValue, + count, + } + } + ) + const { handleSelect, handleClear, isSelected, isActive } = useMultiSelect({ options, paramName: FilterParamName.materialsTerms, diff --git a/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tests.tsx index a8edcb1f11d..540d834f517 100644 --- a/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tests.tsx @@ -1,6 +1,9 @@ import { Aggregations, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import React from "react" -import { sharedAggregateFilterValidation, ValidationParams } from "./AggregationOptionCommonValidation" +import { + sharedAggregateFilterValidation, + ValidationParams, +} from "./AggregationOptionCommonValidation" import { getEssentialProps } from "./helper" import { MediumOptionsScreen } from "./MediumOptions" diff --git a/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tsx index 9955c4ffa09..51f6afd645f 100644 --- a/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/MediumOptions.tsx @@ -9,16 +9,22 @@ import { FilterParamName, ParamDefaultValues, } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import React from "react" import { SingleSelectOptionScreen } from "./SingleSelectOption" -interface MediumOptionsScreenProps extends StackScreenProps {} +interface MediumOptionsScreenProps + extends StackScreenProps {} export const MediumOptionsScreen: React.FC = ({ navigation }) => { const paramName = FilterParamName.medium - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations) const aggregation = aggregationForFilter(paramName, aggregations) diff --git a/src/lib/Components/ArtworkFilter/Filters/MultiSelectCheckOption.tsx b/src/lib/Components/ArtworkFilter/Filters/MultiSelectCheckOption.tsx index e35ff6da05a..75d3a0ee44a 100644 --- a/src/lib/Components/ArtworkFilter/Filters/MultiSelectCheckOption.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/MultiSelectCheckOption.tsx @@ -48,9 +48,14 @@ export const MultiSelectCheckOptionScreen: React.FC {isEnabledImprovedAlertsFlow ? ( - + ) : ( - {filterHeaderText} + + {filterHeaderText} + )} { it("renders the options", () => { const { getAllByTestId } = renderWithWrappersTL( - + ) expect(getAllByTestId("multi-select-option-button").map(extractText)).toEqual([ @@ -44,7 +52,11 @@ describe("MultiSelectOption", () => { describe("searchable", () => { it("filters the options with searchable", () => { const { getAllByTestId, getByTestId } = renderWithWrappersTL( - + ) expect(getAllByTestId("multi-select-option-button").map(extractText)).toEqual([ @@ -60,7 +72,11 @@ describe("MultiSelectOption", () => { it("displays a message indicating no results when nothing matches the search input", () => { const { getAllByTestId, getByTestId, getByText } = renderWithWrappersTL( - + ) expect(getAllByTestId("multi-select-option-button").map(extractText)).toEqual([ diff --git a/src/lib/Components/ArtworkFilter/Filters/MultiSelectOption.tsx b/src/lib/Components/ArtworkFilter/Filters/MultiSelectOption.tsx index 6316c5623a0..f8bcc8acf5e 100644 --- a/src/lib/Components/ArtworkFilter/Filters/MultiSelectOption.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/MultiSelectOption.tsx @@ -124,7 +124,11 @@ export const MultiSelectOptionScreen: React.FC = ( {!!searchable && ( <> - + {filteredOptions.length === 0 && ( @@ -139,7 +143,9 @@ export const MultiSelectOptionScreen: React.FC = ( {useScrollView ? ( {filteredOptions.map((option, index) => ( - {renderItem(option)} + + {renderItem(option)} + ))} {footerComponent} diff --git a/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tests.tsx index 0402a8723a5..b2506ef7ebc 100644 --- a/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tests.tsx @@ -3,7 +3,11 @@ import { extractText } from "lib/tests/extractText" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import React from "react" import { Text } from "react-native" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider, useSelectedOptionsDisplay } from "../ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, + useSelectedOptionsDisplay, +} from "../ArtworkFilterStore" import { getEssentialProps } from "./helper" import { Range } from "./helpers" import { PriceRangeOptionsScreen } from "./PriceRangeOptions" @@ -17,12 +21,19 @@ const DEFAULT_RANGE: Range = { describe("CustomPriceInput", () => { it("renders without error", () => { - renderWithWrappersTL() + renderWithWrappersTL( + + ) }) it("renders the min value", () => { const { getByTestId } = renderWithWrappersTL( - + ) expect(getByTestId("price-min-input").props.value.min).toBe(444) @@ -30,7 +41,12 @@ describe("CustomPriceInput", () => { it("renders the max value", () => { const { getByTestId } = renderWithWrappersTL( - + ) expect(getByTestId("price-max-input").props.value.max).toBe(99999) @@ -39,7 +55,12 @@ describe("CustomPriceInput", () => { it("calls onChange with the min when it is updated", () => { const handleChange = jest.fn() const { getByTestId } = renderWithWrappersTL( - + ) fireEvent.changeText(getByTestId("price-min-input"), "777") @@ -50,7 +71,12 @@ describe("CustomPriceInput", () => { it("calls onChange with the max when it is updated", () => { const handleChange = jest.fn() const { getByTestId } = renderWithWrappersTL( - + ) fireEvent.changeText(getByTestId("price-max-input"), "12345") diff --git a/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tsx index 0232bb3a60e..28045aeafcf 100644 --- a/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/PriceRangeOptions.tsx @@ -6,7 +6,10 @@ import { FilterDisplayName, FilterParamName, } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { Flex, Input, Spacer } from "palette" import React, { useState } from "react" import { parsePriceRangeLabel, parseRange, Range } from "./helpers" @@ -32,13 +35,19 @@ const PRICE_RANGE_OPTIONS: FilterData[] = [ ] export const PriceRangeOptionsScreen: React.FC = ({ navigation }) => { - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const selectedOptions = useSelectedOptionsDisplay() const selectedFilterOption = selectedOptions.find((option) => option.paramName === PARAM_NAME)! - const isCustomOption = PRICE_RANGE_OPTIONS.every((option) => option.paramValue !== selectedFilterOption.paramValue) + const isCustomOption = PRICE_RANGE_OPTIONS.every( + (option) => option.paramValue !== selectedFilterOption.paramValue + ) const [customPriceValue, setCustomPriceValue] = useState( - parseRange(isCustomOption ? (selectedFilterOption.paramValue as string) : DEFAULT_PRICE_OPTION.paramValue) + parseRange( + isCustomOption ? (selectedFilterOption.paramValue as string) : DEFAULT_PRICE_OPTION.paramValue + ) ) const [customSelected, setCustomSelected] = useState(isCustomOption) const selectedOption = customSelected ? DEFAULT_PRICE_OPTION : selectedFilterOption diff --git a/src/lib/Components/ArtworkFilter/Filters/SingleSelectOption.tsx b/src/lib/Components/ArtworkFilter/Filters/SingleSelectOption.tsx index b6bf1326195..0d0ed600f89 100644 --- a/src/lib/Components/ArtworkFilter/Filters/SingleSelectOption.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/SingleSelectOption.tsx @@ -44,7 +44,12 @@ export const SingleSelectOptionScreen: React.FC = const renderItem = (item: FilterData | JSX.Element) => { if (isFilterData(item)) { return ( - + ) } diff --git a/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tests.tsx index 4900e8cafad..3b444612308 100644 --- a/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tests.tsx @@ -5,9 +5,18 @@ import React from "react" import { Text } from "react-native" import { ReactTestInstance } from "react-test-renderer" import { FilterArray, FilterData, FilterParamName } from "../ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider, useSelectedOptionsDisplay } from "../ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, + useSelectedOptionsDisplay, +} from "../ArtworkFilterStore" import { getEssentialProps } from "./helper" -import { checkIsEmptyCustomValues, CustomSize, getCustomValues, SizesOptionsScreen } from "./SizesOptionsScreen" +import { + checkIsEmptyCustomValues, + CustomSize, + getCustomValues, + SizesOptionsScreen, +} from "./SizesOptionsScreen" // Helpers const getFilters = (element: ReactTestInstance) => { @@ -54,7 +63,9 @@ describe("SizesOptionsScreen", () => { ) } - const TestRenderer = ({ initialData = INITIAL_DATA }: { initialData?: ArtworkFiltersState } = {}) => { + const TestRenderer = ({ + initialData = INITIAL_DATA, + }: { initialData?: ArtworkFiltersState } = {}) => { return ( @@ -177,7 +188,9 @@ describe("SizesOptionsScreen", () => { }) it("should keep custom inputs filled in if a predefined value is selected", () => { - const { getByA11yLabel, getByDisplayValue, getByText } = renderWithWrappersTL() + const { getByA11yLabel, getByDisplayValue, getByText } = renderWithWrappersTL( + + ) fireEvent.changeText(getByA11yLabel("Minimum Width Input"), "5") fireEvent.changeText(getByA11yLabel("Maximum Width Input"), "10") @@ -188,7 +201,9 @@ describe("SizesOptionsScreen", () => { }) it("should clear the previously selected option if a custom value is entered", () => { - const { getByText, getByA11yLabel, getAllByA11yState, getByTestId } = renderWithWrappersTL() + const { getByText, getByA11yLabel, getAllByA11yState, getByTestId } = renderWithWrappersTL( + + ) fireEvent.press(getByText("Small (under 16in)")) fireEvent.changeText(getByA11yLabel("Minimum Width Input"), "5") @@ -322,7 +337,9 @@ describe("SizesOptionsScreen", () => { }) it('should clear selected custom values if "Clear" button is pressed', () => { - const { getByText, getByA11yLabel, queryAllByA11yState } = renderWithWrappersTL() + const { getByText, getByA11yLabel, queryAllByA11yState } = renderWithWrappersTL( + + ) fireEvent.changeText(getByA11yLabel("Minimum Width Input"), "5") fireEvent.press(getByText("Clear")) diff --git a/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tsx b/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tsx index ef7b65cce02..08592071fe8 100644 --- a/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/SizesOptionsScreen.tsx @@ -14,7 +14,8 @@ export interface CustomSize { height: Range } -interface SizesOptionsScreenProps extends StackScreenProps {} +interface SizesOptionsScreenProps + extends StackScreenProps {} interface CustomSizeInputsContainerProps { values: CustomSize active?: boolean @@ -70,7 +71,10 @@ const DEFAULT_CUSTOM_SIZE: CustomSize = { }, } -const CUSTOM_SIZE_OPTION_KEYS: Array = [FilterParamName.width, FilterParamName.height] +const CUSTOM_SIZE_OPTION_KEYS: Array = [ + FilterParamName.width, + FilterParamName.height, +] // Helpers export const getCustomValues = (options: FilterData[]) => { @@ -94,7 +98,11 @@ export const checkIsEmptyCustomValues = (values: CustomSize) => { }) } -const CustomSizeInputsContainer: React.FC = ({ values, active, onChange }) => { +const CustomSizeInputsContainer: React.FC = ({ + values, + active, + onChange, +}) => { const handleChange = (paramName: FilterParamName) => (range: Range) => { onChange({ ...values, [paramName]: range }) } @@ -119,7 +127,9 @@ const CustomSizeInputsContainer: React.FC = ({ v } export const SizesOptionsScreen: React.FC = ({ navigation }) => { - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const { handleSelect, isSelected, @@ -135,7 +145,9 @@ export const SizesOptionsScreen: React.FC = ({ navigati CUSTOM_SIZE_OPTION_KEYS.includes(option.paramName as keyof CustomSize) ) const [customValues, setCustomValues] = useState(getCustomValues(selectedCustomOptions)) - const [customSizeSelected, setCustomSizeSelected] = useState(!checkIsEmptyCustomValues(customValues)) + const [customSizeSelected, setCustomSizeSelected] = useState( + !checkIsEmptyCustomValues(customValues) + ) const [key, setKey] = useState(0) const shouldShowCustomInputs = filterType !== "auctionResult" const isActive = isActivePredefinedValues || !checkIsEmptyCustomValues(customValues) diff --git a/src/lib/Components/ArtworkFilter/Filters/SortOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/SortOptions.tests.tsx index eb49e98fbb2..6207492b371 100644 --- a/src/lib/Components/ArtworkFilter/Filters/SortOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/SortOptions.tests.tsx @@ -24,7 +24,11 @@ describe("Sort Options Screen", () => { }, } - const MockSortScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => ( + const MockSortScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => ( @@ -32,7 +36,9 @@ describe("Sort Options Screen", () => { const selectedSortOption = (componentTree: ReactTestRenderer) => { const innerOptions = componentTree.root.findAllByType(InnerOptionListItem) - const selectedOption = innerOptions.filter((item) => item.findByType(RadioDot).props.selected)[0] + const selectedOption = innerOptions.filter( + (item) => item.findByType(RadioDot).props.selected + )[0] return selectedOption } diff --git a/src/lib/Components/ArtworkFilter/Filters/SortOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/SortOptions.tsx index 1d4446d6799..3041d412474 100644 --- a/src/lib/Components/ArtworkFilter/Filters/SortOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/SortOptions.tsx @@ -1,11 +1,19 @@ import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import React from "react" import { SingleSelectOptionScreen } from "./SingleSelectOption" -interface SortOptionsScreenProps extends StackScreenProps {} +interface SortOptionsScreenProps + extends StackScreenProps {} // Sorting types enum ArtworkSorts { @@ -132,10 +140,14 @@ export const ORDERED_AUCTION_RESULTS_SORTS: FilterData[] = [ export const SortOptionsScreen: React.FC = ({ navigation }) => { const filterType = ArtworksFiltersStore.useStoreState((state) => state.filterType) const localSortOptions = ArtworksFiltersStore.useStoreState((state) => state.sortOptions) - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const selectedOptions = useSelectedOptionsDisplay() - const selectedOption = selectedOptions.find((option) => option.paramName === FilterParamName.sort)! + const selectedOption = selectedOptions.find( + (option) => option.paramName === FilterParamName.sort + )! const filterOptions = { artwork: [DEFAULT_ARTWORK_SORT, ...ORDERED_ARTWORK_SORTS], diff --git a/src/lib/Components/ArtworkFilter/Filters/TimePeriodOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/TimePeriodOptions.tests.tsx index dfdeb1dca78..94db0044eb2 100644 --- a/src/lib/Components/ArtworkFilter/Filters/TimePeriodOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/TimePeriodOptions.tests.tsx @@ -43,7 +43,11 @@ describe("TimePeriodOptions Screen", () => { selectedFilters: [], } - const MockTimePeriodOptionsScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { + const MockTimePeriodOptionsScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => { return ( @@ -59,7 +63,9 @@ describe("TimePeriodOptions Screen", () => { }) it("renders all options present in the aggregation", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("2020–Today")).toBeTruthy() expect(getByText("2010–2019")).toBeTruthy() @@ -86,7 +92,9 @@ describe("TimePeriodOptions Screen", () => { }) it("toggles selected filters 'ON' and unselected filters 'OFF", async () => { - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const options = getAllByA11yState({ checked: true }) expect(options).toHaveLength(1) diff --git a/src/lib/Components/ArtworkFilter/Filters/ViewAsOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/ViewAsOptions.tsx index e3c3d237738..99fd53c22d3 100644 --- a/src/lib/Components/ArtworkFilter/Filters/ViewAsOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/ViewAsOptions.tsx @@ -7,14 +7,20 @@ import { ViewAsValues, } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { FilterData } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import React from "react" import { SingleSelectOptionScreen } from "./SingleSelectOption" -interface ViewAsOptionsScreenProps extends StackScreenProps {} +interface ViewAsOptionsScreenProps + extends StackScreenProps {} export const ViewAsOptionsScreen: React.FC = ({ navigation }) => { - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((action) => action.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (action) => action.selectFiltersAction + ) const paramName = FilterParamName.viewAs diff --git a/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tests.tsx index d4bec657c71..59cc70a307b 100644 --- a/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tests.tsx @@ -1,5 +1,8 @@ import { FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { MockFilterScreen } from "lib/Components/ArtworkFilter/FilterTestHelper" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import React from "react" @@ -20,7 +23,11 @@ describe("Ways to Buy Options Screen", () => { }, } - const MockWaysToBuyScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => ( + const MockWaysToBuyScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => ( @@ -109,7 +116,9 @@ describe("Ways to Buy Options Screen", () => { }, } - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const options = getAllByA11yState({ checked: true }) expect(options).toHaveLength(1) @@ -142,7 +151,9 @@ describe("Ways to Buy Options Screen", () => { }, } - const { getAllByA11yState } = renderWithWrappersTL() + const { getAllByA11yState } = renderWithWrappersTL( + + ) const options = getAllByA11yState({ checked: true }) expect(options).toHaveLength(1) diff --git a/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tsx index b9e896cec28..6c6aebc55a8 100644 --- a/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/WaysToBuyOptions.tsx @@ -1,6 +1,13 @@ import { StackScreenProps } from "@react-navigation/stack" -import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + FilterData, + FilterDisplayName, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import React, { useState } from "react" import { ArtworkFilterNavigationStack } from "../ArtworkFilterNavigator" import { MultiSelectOptionScreen } from "./MultiSelectOption" @@ -30,7 +37,9 @@ export const WAYS_TO_BUY_OPTIONS: FilterData[] = [ export const WAYS_TO_BUY_PARAM_NAMES = WAYS_TO_BUY_OPTIONS.map((option) => option.paramName) export const WaysToBuyOptionsScreen: React.FC = ({ navigation }) => { - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const selectedOptions = useSelectedOptionsDisplay() const options = WAYS_TO_BUY_OPTIONS.map((option) => { @@ -72,7 +81,9 @@ export const WaysToBuyOptionsScreen: React.FC = ({ filterHeaderText={FilterDisplayName.waysToBuy} filterOptions={options} navigation={navigation} - {...(selected.length > 0 ? { rightButtonText: "Clear", onRightButtonPress: handleClear } : {})} + {...(selected.length > 0 + ? { rightButtonText: "Clear", onRightButtonPress: handleClear } + : {})} /> ) } diff --git a/src/lib/Components/ArtworkFilter/Filters/YearOptions.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/YearOptions.tests.tsx index 3b917ae7acd..57d149ae076 100644 --- a/src/lib/Components/ArtworkFilter/Filters/YearOptions.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/YearOptions.tests.tsx @@ -10,7 +10,12 @@ import { renderWithWrappers } from "lib/tests/renderWithWrappers" import React from "react" import { act } from "react-test-renderer" import { getEssentialProps } from "./helper" -import { ALLOW_EMPTY_CREATED_DATES_FILTER, OptionItem, YearOptionsScreen, YearText } from "./YearOptions" +import { + ALLOW_EMPTY_CREATED_DATES_FILTER, + OptionItem, + YearOptionsScreen, + YearText, +} from "./YearOptions" describe("Year Options Screen", () => { let storeInstance: ReturnType @@ -53,7 +58,11 @@ describe("Year Options Screen", () => { return null } - const MockYearOptionsScreen = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => ( + const MockYearOptionsScreen = ({ + initialData = initialState, + }: { + initialData?: ArtworkFiltersState + }) => ( @@ -64,7 +73,9 @@ describe("Year Options Screen", () => { const tree = renderWithWrappers() expect(extractText(tree.root.findAllByType(YearText)[0])).toEqual("2010 – 2021") - expect(extractText(tree.root.findAllByType(OptionItem)[0])).toEqual(ALLOW_EMPTY_CREATED_DATES_FILTER.displayText) + expect(extractText(tree.root.findAllByType(OptionItem)[0])).toEqual( + ALLOW_EMPTY_CREATED_DATES_FILTER.displayText + ) }) it("selects the right year range and option", () => { diff --git a/src/lib/Components/ArtworkFilter/Filters/YearOptions.tsx b/src/lib/Components/ArtworkFilter/Filters/YearOptions.tsx index af77cd0840b..8e5c449556b 100644 --- a/src/lib/Components/ArtworkFilter/Filters/YearOptions.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/YearOptions.tsx @@ -1,8 +1,15 @@ import MultiSlider from "@ptomasroos/react-native-multi-slider" import { StackScreenProps } from "@react-navigation/stack" import { ArtworkFilterNavigationStack } from "lib/Components/ArtworkFilter" -import { aggregationForFilter, FilterData, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworksFiltersStore, useSelectedOptionsDisplay } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + aggregationForFilter, + FilterData, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + ArtworksFiltersStore, + useSelectedOptionsDisplay, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { ArtworkFilterBackHeader } from "lib/Components/ArtworkFilter/components/ArtworkFilterBackHeader" import { CircleWithBorder } from "lib/Components/CircleWithBorder/CircleWithBorder" import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader" @@ -14,7 +21,8 @@ import React, { useState } from "react" import Haptic from "react-native-haptic-feedback" import styled from "styled-components/native" -interface YearOptionsScreenProps extends StackScreenProps {} +interface YearOptionsScreenProps + extends StackScreenProps {} export const ALLOW_EMPTY_CREATED_DATES_FILTER: FilterData = { displayText: "Include Lots without Artwork Date Listed", @@ -31,7 +39,9 @@ export const YearOptionsScreen: React.FC = ({ navigation const selectedFilters = ArtworksFiltersStore.useStoreState((state) => state.selectedFilters) const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations) - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const artistEarliestCreatedYear = Number( aggregationForFilter(FilterParamName.earliestCreatedYear, aggregations)?.counts[0].value @@ -159,7 +169,14 @@ interface OptionItemProps { export const OptionItem = ({ onPress, text, selected }: OptionItemProps) => ( - + {text} {!!selected && ( diff --git a/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.tests.tsx b/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.tests.tsx index 606d8e2d1eb..fa0421ae150 100644 --- a/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.tests.tsx +++ b/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.tests.tsx @@ -80,15 +80,21 @@ describe("useMultiSelect", () => { buttons[0].props.onPress() - expect(extractText(tree.root.findByProps({ testID: "nextParamValues" }))).toEqual('["example-1"]') + expect(extractText(tree.root.findByProps({ testID: "nextParamValues" }))).toEqual( + '["example-1"]' + ) buttons[2].props.onPress() - expect(extractText(tree.root.findByProps({ testID: "nextParamValues" }))).toEqual('["example-1","example-3"]') + expect(extractText(tree.root.findByProps({ testID: "nextParamValues" }))).toEqual( + '["example-1","example-3"]' + ) buttons[0].props.onPress() - expect(extractText(tree.root.findByProps({ testID: "nextParamValues" }))).toEqual('["example-3"]') + expect(extractText(tree.root.findByProps({ testID: "nextParamValues" }))).toEqual( + '["example-3"]' + ) }) it("dispatches filter updates", async () => { diff --git a/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.ts b/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.ts index afd5a197837..f5c9ded79fc 100644 --- a/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.ts +++ b/src/lib/Components/ArtworkFilter/Filters/useMultiSelect.ts @@ -10,12 +10,20 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react" // Default value is always empty array since this is a multi-select const DEFAULT_VALUE: string[] = [] -export const useMultiSelect = ({ options, paramName }: { options: FilterData[]; paramName: FilterParamName }) => { +export const useMultiSelect = ({ + options, + paramName, +}: { + options: FilterData[] + paramName: FilterParamName +}) => { const defaultFilter = DEFAULT_FILTERS.find((option) => option.paramName === paramName) const didMountRef = useRef(false) - const selectFiltersAction = ArtworksFiltersStore.useStoreActions((state) => state.selectFiltersAction) + const selectFiltersAction = ArtworksFiltersStore.useStoreActions( + (state) => state.selectFiltersAction + ) const selectedOptions = useSelectedOptionsDisplay() @@ -25,7 +33,8 @@ export const useMultiSelect = ({ options, paramName }: { options: FilterData[]; // Array of selected paramValues: the value that's actually dispatched const [nextParamValues, setNextParamValues] = useState( - typeof selectedParamOptions?.paramValue === "object" && every(selectedParamOptions.paramValue, isString) + typeof selectedParamOptions?.paramValue === "object" && + every(selectedParamOptions.paramValue, isString) ? selectedParamOptions.paramValue : [] ) @@ -96,7 +105,9 @@ export const useMultiSelect = ({ options, paramName }: { options: FilterData[]; paramName, // Label which appears on the filter overview screen displayText: - nextOptions.map(({ displayText }) => displayText).join(", ") || defaultFilter?.displayText || "All", + nextOptions.map(({ displayText }) => displayText).join(", ") || + defaultFilter?.displayText || + "All", // Array of paramValues paramValue: nextParamValues, }) diff --git a/src/lib/Components/ArtworkFilter/SavedSearch/convertersToFilterParams.ts b/src/lib/Components/ArtworkFilter/SavedSearch/convertersToFilterParams.ts index f6efde8c355..a83659b1541 100644 --- a/src/lib/Components/ArtworkFilter/SavedSearch/convertersToFilterParams.ts +++ b/src/lib/Components/ArtworkFilter/SavedSearch/convertersToFilterParams.ts @@ -17,7 +17,9 @@ import { SearchCriteria, SearchCriteriaAttributes } from "./types" export type AggregationByFilterParamName = Dictionary -export const convertPriceToFilterParam = (criteria: SearchCriteriaAttributes): FilterData | null => { +export const convertPriceToFilterParam = ( + criteria: SearchCriteriaAttributes +): FilterData | null => { const priceRangeValue = criteria[SearchCriteria.priceRange] if (!isNil(priceRangeValue)) { @@ -47,7 +49,9 @@ export const convertCustomSizeToFilterParamByName = (paramName: FilterParamName, } } -export const convertSizeToFilterParams = (criteria: SearchCriteriaAttributes): FilterData[] | null => { +export const convertSizeToFilterParams = ( + criteria: SearchCriteriaAttributes +): FilterData[] | null => { const filterParams: FilterData[] = [] const dimensionRangeValue = criteria.dimensionRange const widthValue = criteria[SearchCriteria.width] @@ -56,7 +60,9 @@ export const convertSizeToFilterParams = (criteria: SearchCriteriaAttributes): F // Convert old size filter format to new if (!isNil(dimensionRangeValue) && dimensionRangeValue !== "0-*") { - const sizeOptionItem = FALLBACK_SIZE_OPTIONS.find((option) => option.oldParamValue === dimensionRangeValue) + const sizeOptionItem = FALLBACK_SIZE_OPTIONS.find( + (option) => option.oldParamValue === dimensionRangeValue + ) if (sizeOptionItem) { filterParams.push({ @@ -128,7 +134,9 @@ export const convertAggregationValueNamesToFilterParam = ( criteriaValues: string[] ): FilterData | null => { const aggregationByValue = keyBy(aggregations, "value") - const availableValues = criteriaValues.filter((criteriaValue) => !!aggregationByValue[criteriaValue]) + const availableValues = criteriaValues.filter( + (criteriaValue) => !!aggregationByValue[criteriaValue] + ) const names = availableValues.map((value) => aggregationByValue[value].name) if (availableValues.length > 0) { @@ -142,13 +150,19 @@ export const convertAggregationValueNamesToFilterParam = ( return null } -export const convertAttributionToFilterParam = (criteria: SearchCriteriaAttributes): FilterData | null => { +export const convertAttributionToFilterParam = ( + criteria: SearchCriteriaAttributes +): FilterData | null => { const attributionValues = criteria[SearchCriteria.attributionClass] if (Array.isArray(attributionValues) && attributionValues.length > 0) { const attributionItemByValue = keyBy(ATTRIBUTION_CLASS_OPTIONS, "paramValue") - const availableAttributions = attributionValues.filter((attribution) => !!attributionItemByValue[attribution]) - const names = availableAttributions.map((attribution) => attributionItemByValue[attribution].displayText) + const availableAttributions = attributionValues.filter( + (attribution) => !!attributionItemByValue[attribution] + ) + const names = availableAttributions.map( + (attribution) => attributionItemByValue[attribution].displayText + ) if (availableAttributions.length > 0) { return { @@ -162,7 +176,9 @@ export const convertAttributionToFilterParam = (criteria: SearchCriteriaAttribut return null } -export const convertWaysToBuyToFilterParams = (criteria: SearchCriteriaAttributes): FilterData[] | null => { +export const convertWaysToBuyToFilterParams = ( + criteria: SearchCriteriaAttributes +): FilterData[] | null => { const options = WAYS_TO_BUY_OPTIONS.filter((option) => { return !isNil(criteria[option.paramName as unknown as SearchCriteria]) }) @@ -177,7 +193,9 @@ export const convertWaysToBuyToFilterParams = (criteria: SearchCriteriaAttribute return null } -export const convertMajorPeriodToFilterParam = (criteria: SearchCriteriaAttributes): FilterData | null => { +export const convertMajorPeriodToFilterParam = ( + criteria: SearchCriteriaAttributes +): FilterData | null => { const periods = criteria[SearchCriteria.majorPeriods] if (Array.isArray(periods) && periods.length > 0) { @@ -198,7 +216,10 @@ export const convertSavedSearchCriteriaToFilterParams = ( aggregations: Aggregations ): FilterData[] => { let filterParams: FilterData[] = [] - const aggregationByFilterParamName = keyBy(aggregations, (aggregation) => filterKeyFromAggregation[aggregation.slice]) + const aggregationByFilterParamName = keyBy( + aggregations, + (aggregation) => filterKeyFromAggregation[aggregation.slice] + ) const aggregationValueByFilterParamName = mapValues( aggregationByFilterParamName, "counts" diff --git a/src/lib/Components/ArtworkFilter/SavedSearch/searchCriteriaHelpers.ts b/src/lib/Components/ArtworkFilter/SavedSearch/searchCriteriaHelpers.ts index 957f3eea459..b86d59a1e41 100644 --- a/src/lib/Components/ArtworkFilter/SavedSearch/searchCriteriaHelpers.ts +++ b/src/lib/Components/ArtworkFilter/SavedSearch/searchCriteriaHelpers.ts @@ -27,7 +27,9 @@ export const getOnlyFilledSearchCriteriaValues = (searchCriteria: SearchCriteria } export const getAllowedFiltersForSavedSearchInput = (filters: FilterArray) => { - return filters.filter((filter) => allowedSearchCriteriaKeys.includes(filter.paramName as unknown as SearchCriteria)) + return filters.filter((filter) => + allowedSearchCriteriaKeys.includes(filter.paramName as unknown as SearchCriteria) + ) } export const prepareFilterDataForSaveSearchInput = (filters: FilterData[]) => { diff --git a/src/lib/Components/ArtworkFilter/components/ArtworkFilterApplyButton.tsx b/src/lib/Components/ArtworkFilter/components/ArtworkFilterApplyButton.tsx index f27e955459c..06c86ee8227 100644 --- a/src/lib/Components/ArtworkFilter/components/ArtworkFilterApplyButton.tsx +++ b/src/lib/Components/ArtworkFilter/components/ArtworkFilterApplyButton.tsx @@ -65,7 +65,14 @@ export const ArtworkFilterApplyButton: React.FC = elevation: 12, }} > - + {!!shouldShowCreateAlertButton && ( <> { it('should call "onLeftButtonPress" handler when left button is pressed', () => { const onLeftButtonPressMock = jest.fn() - const { getByA11yLabel } = renderWithWrappersTL() + const { getByA11yLabel } = renderWithWrappersTL( + + ) fireEvent.press(getByA11yLabel("Header back button")) diff --git a/src/lib/Components/ArtworkFilter/components/ArtworkFilterBackHeader.tsx b/src/lib/Components/ArtworkFilter/components/ArtworkFilterBackHeader.tsx index 2c9520898d2..9413ea1ee1c 100644 --- a/src/lib/Components/ArtworkFilter/components/ArtworkFilterBackHeader.tsx +++ b/src/lib/Components/ArtworkFilter/components/ArtworkFilterBackHeader.tsx @@ -22,7 +22,13 @@ export const ArtworkFilterBackHeader: React.FC = ( return ( <> - + { }) it("should render passed rightButtonText prop", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) expect(getByText("Custom Right Button Text")).toBeTruthy() }) @@ -48,7 +53,9 @@ describe("ArtworkFilterOptionsHeader", () => { it('should call "onLeftButtonPress" handler when back button is pressed', () => { const onLeftButtonPressMock = jest.fn() - const { getByA11yLabel } = renderWithWrappersTL() + const { getByA11yLabel } = renderWithWrappersTL( + + ) fireEvent.press(getByA11yLabel("Header back button")) @@ -57,7 +64,9 @@ describe("ArtworkFilterOptionsHeader", () => { it('should call "onRightButtonPress" handler when clear all is pressed', () => { const onRightButtonPressMock = jest.fn() - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) fireEvent.press(getByText("Clear")) diff --git a/src/lib/Components/ArtworkFilter/useArtworkFilters.ts b/src/lib/Components/ArtworkFilter/useArtworkFilters.ts index 880c1ca979d..de2d6d4925f 100644 --- a/src/lib/Components/ArtworkFilter/useArtworkFilters.ts +++ b/src/lib/Components/ArtworkFilter/useArtworkFilters.ts @@ -31,7 +31,9 @@ export const useArtworkFilters = ({ onRefetch, type = "filter", }: UseArtworkFiltersOptions) => { - const setAggregationsAction = ArtworksFiltersStore.useStoreActions((state) => state.setAggregationsAction) + const setAggregationsAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setAggregationsAction + ) const appliedFilters = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) const applyFilters = ArtworksFiltersStore.useStoreState((state) => state.applyFilters) const filterType = ArtworksFiltersStore.useStoreState((state) => state.filterType) @@ -54,7 +56,9 @@ export const useArtworkFilters = ({ onRefetch(error) } if (error) { - const errorMessage = componentPath ? `${componentPath} ${type} error: ${error.message}` : error.message + const errorMessage = componentPath + ? `${componentPath} ${type} error: ${error.message}` + : error.message throw new Error(errorMessage) } }, @@ -71,7 +75,9 @@ export const useArtworkFiltersAggregation = ({ paramName }: { paramName: FilterP const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations) const selectedFilters = ArtworksFiltersStore.useStoreState((state) => state.selectedFilters) const filterType = ArtworksFiltersStore.useStoreState((state) => state.filterType) - const previouslyAppliedFilters = ArtworksFiltersStore.useStoreState((state) => state.previouslyAppliedFilters) + const previouslyAppliedFilters = ArtworksFiltersStore.useStoreState( + (state) => state.previouslyAppliedFilters + ) const aggregation = aggregationForFilter(paramName, aggregations) @@ -92,7 +98,11 @@ export const useArtworkFiltersAggregation = ({ paramName }: { paramName: FilterP export const useSelectedFiltersCount = () => { const appliedFilters = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) return useMemo( - () => Object.values(getSelectedFiltersCounts(appliedFilters)).reduce((prev, value) => prev + value, 0), + () => + Object.values(getSelectedFiltersCounts(appliedFilters)).reduce( + (prev, value) => prev + value, + 0 + ), [appliedFilters] ) } diff --git a/src/lib/Components/ArtworkGrids/ArtworkGridItem.tests.tsx b/src/lib/Components/ArtworkGrids/ArtworkGridItem.tests.tsx index 5941e6c1b30..45c089be86f 100644 --- a/src/lib/Components/ArtworkGrids/ArtworkGridItem.tests.tsx +++ b/src/lib/Components/ArtworkGrids/ArtworkGridItem.tests.tsx @@ -26,7 +26,9 @@ describe("tracking", () => { it("sends an event when trackTap is passed", () => { const trackTap = jest.fn() - const rendered = renderWithWrappers() + const rendered = renderWithWrappers( + + ) const touchableArtwork = rendered.root.findByType(Touchable) act(() => touchableArtwork.props.onPress()) @@ -161,7 +163,9 @@ describe("in a closed sale", () => { // is_open: false (this would be returned from Metaphysics, though we don't fetch this field) }, } - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(extractText(tree.root)).not.toContain("partner") }) @@ -174,7 +178,9 @@ describe("in a closed sale", () => { // is_open: false (this would be returned from Metaphysics, though we don't fetch this field) }, } - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(extractText(tree.root)).toContain("partner") }) diff --git a/src/lib/Components/ArtworkGrids/ArtworkGridItem.tsx b/src/lib/Components/ArtworkGrids/ArtworkGridItem.tsx index 22604d54b8f..2e34656676f 100644 --- a/src/lib/Components/ArtworkGrids/ArtworkGridItem.tsx +++ b/src/lib/Components/ArtworkGrids/ArtworkGridItem.tsx @@ -6,7 +6,11 @@ import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView" import { navigate } from "lib/navigation/navigate" import { GlobalStore } from "lib/store/GlobalStore" import { getUrgencyTag } from "lib/utils/getUrgencyTag" -import { PlaceholderBox, PlaceholderRaggedText, RandomNumberGenerator } from "lib/utils/placeholders" +import { + PlaceholderBox, + PlaceholderRaggedText, + RandomNumberGenerator, +} from "lib/utils/placeholders" import { Box, Flex, Sans, Spacer, Text, TextProps, Touchable } from "palette" import React, { useRef } from "react" import { View } from "react-native" @@ -136,8 +140,13 @@ export const Artwork: React.FC = ({ {!!artwork.image && ( - - {Boolean(!hideUrgencyTags && urgencyTag && artwork?.sale?.isAuction && !artwork?.sale?.isClosed) && ( + + {Boolean( + !hideUrgencyTags && urgencyTag && artwork?.sale?.isAuction && !artwork?.sale?.isClosed + ) && ( = ({ )} {!!artwork.artistNames && ( - + {artwork.artistNames} )} {!!artwork.title && ( - + {artwork.title} @@ -175,12 +197,24 @@ export const Artwork: React.FC = ({ )} {!hidePartner && !!artwork.partner?.name && ( - + {artwork.partner.name} )} {!!saleInfo && !hideSaleInfo && ( - + {saleInfo} )} @@ -281,7 +315,9 @@ export default createFragmentContainer(Artwork, { `, }) -export const ArtworkGridItemPlaceholder: React.FC<{ seed?: number }> = ({ seed = Math.random() }) => { +export const ArtworkGridItemPlaceholder: React.FC<{ seed?: number }> = ({ + seed = Math.random(), +}) => { const rng = new RandomNumberGenerator(seed) return ( diff --git a/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.stories.tsx b/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.stories.tsx index 4cf6d772e70..0585deed74b 100644 --- a/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.stories.tsx +++ b/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.stories.tsx @@ -18,8 +18,11 @@ storiesOf("ArtworkFilterHeader", module) const selectedFiltersCount = useSelectedFiltersCount() return ( - {/* tslint:disable-next-line:no-empty */} - {}} /> + {}} + /> ) }) diff --git a/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.tsx b/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.tsx index 1fdbc5435fc..ebf68bfe0f1 100644 --- a/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.tsx +++ b/src/lib/Components/ArtworkGrids/ArtworksFilterHeader.tsx @@ -20,7 +20,13 @@ export const ArtworksFilterHeader: React.FC = ({ }) => { return ( - + {childrenPosition === "left" && children} { }) it(`does not call "trackClear" callback on "Clear filters" button press if id is not passed`, () => { - const { queryAllByText } = renderWithWrappersTL() + const { queryAllByText } = renderWithWrappersTL( + + ) fireEvent(queryAllByText("Clear filters")[0], "press") expect(trackClearMock).not.toHaveBeenCalled() }) it(`does not call "trackClear" callback on "Clear filters" button press if slug is not passed`, () => { - const { queryAllByText } = renderWithWrappersTL() + const { queryAllByText } = renderWithWrappersTL( + + ) fireEvent(queryAllByText("Clear filters")[0], "press") expect(trackClearMock).not.toHaveBeenCalled() }) diff --git a/src/lib/Components/ArtworkGrids/FilteredArtworkGridZeroState.tsx b/src/lib/Components/ArtworkGrids/FilteredArtworkGridZeroState.tsx index 46c1f9c1e62..d4dbd5d3203 100644 --- a/src/lib/Components/ArtworkGrids/FilteredArtworkGridZeroState.tsx +++ b/src/lib/Components/ArtworkGrids/FilteredArtworkGridZeroState.tsx @@ -13,7 +13,9 @@ export interface ZeroStateProps { export const FilteredArtworkGridZeroState: React.FC = (props) => { const { id, slug, trackClear, hideClearButton } = props - const clearFiltersZeroStateAction = ArtworksFiltersStore.useStoreActions((state) => state.clearFiltersZeroStateAction) + const clearFiltersZeroStateAction = ArtworksFiltersStore.useStoreActions( + (state) => state.clearFiltersZeroStateAction + ) return ( diff --git a/src/lib/Components/ArtworkGrids/GenericGrid.tsx b/src/lib/Components/ArtworkGrids/GenericGrid.tsx index db66d5a9dfe..8cecb657ac0 100644 --- a/src/lib/Components/ArtworkGrids/GenericGrid.tsx +++ b/src/lib/Components/ArtworkGrids/GenericGrid.tsx @@ -28,7 +28,9 @@ interface State { type PropsForArtwork = Omit -type GenericArtworkType = GenericGrid_artworks extends ReadonlyArray ? GenericArtwork : never +type GenericArtworkType = GenericGrid_artworks extends ReadonlyArray + ? GenericArtwork + : never export class GenericArtworksGrid extends React.Component { static defaultProps = { @@ -146,7 +148,9 @@ export class GenericArtworksGrid extends React.Component ) if (row < artworks.length - 1) { - artworkComponents.push() + artworkComponents.push( + + ) } } @@ -155,7 +159,11 @@ export class GenericArtworksGrid extends React.Component + {artworkComponents} ) diff --git a/src/lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid.tsx b/src/lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid.tsx index fa7223d3ebc..a1a06b13f1c 100644 --- a/src/lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid.tsx +++ b/src/lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid.tsx @@ -115,7 +115,9 @@ export interface Props { } interface PrivateProps { - connection: InfiniteScrollArtworksGrid_connection | InfiniteScrollArtworksGrid_myCollectionConnection + connection: + | InfiniteScrollArtworksGrid_connection + | InfiniteScrollArtworksGrid_myCollectionConnection loadMore: RelayPaginationProp["loadMore"] hasMore: RelayPaginationProp["hasMore"] } @@ -252,7 +254,8 @@ class InfiniteScrollArtworksGrid extends React.Component { // There are artworks without images and other ‘issues’. Like Force we’re just going to reject those for now. @@ -300,7 +303,9 @@ class InfiniteScrollArtworksGrid extends React.Component + ) } } @@ -333,7 +342,11 @@ class InfiniteScrollArtworksGrid extends React.Component + {artworkComponents} ) @@ -417,7 +430,9 @@ class InfiniteScrollArtworksGrid extends React.Component - {!!this.props.autoFetch && } + {!!this.props.autoFetch && ( + + )} )} @@ -442,29 +457,32 @@ const styles = StyleSheet.create({ }, }) -export const InfiniteScrollArtworksGridContainer = createFragmentContainer(InfiniteScrollArtworksGridMapper, { - connection: graphql` - fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface - @argumentDefinitions(skipMyCollection: { type: "Boolean", defaultValue: true }) { - pageInfo { - hasNextPage - startCursor - endCursor - } - edges { - node { - slug - id - image { - aspectRatio +export const InfiniteScrollArtworksGridContainer = createFragmentContainer( + InfiniteScrollArtworksGridMapper, + { + connection: graphql` + fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface + @argumentDefinitions(skipMyCollection: { type: "Boolean", defaultValue: true }) { + pageInfo { + hasNextPage + startCursor + endCursor + } + edges { + node { + slug + id + image { + aspectRatio + } + ...ArtworkGridItem_artwork + ...MyCollectionArtworkListItem_artwork @skip(if: $skipMyCollection) } - ...ArtworkGridItem_artwork - ...MyCollectionArtworkListItem_artwork @skip(if: $skipMyCollection) } } - } - `, -}) + `, + } +) /** Same as InfiniteScrollArtworksGridContainer but for MyCollection Artworks */ export const InfiniteScrollMyCollectionArtworksGridContainer = createFragmentContainer( diff --git a/src/lib/Components/ArtworkGrids/SaleArtworkGridItem.tsx b/src/lib/Components/ArtworkGrids/SaleArtworkGridItem.tsx index 26382f398da..3bba6673171 100644 --- a/src/lib/Components/ArtworkGrids/SaleArtworkGridItem.tsx +++ b/src/lib/Components/ArtworkGrids/SaleArtworkGridItem.tsx @@ -3,7 +3,11 @@ import { SaleArtworkGridItem_saleArtwork } from "__generated__/SaleArtworkGridIt import { filterArtworksParams } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { ArtworksFiltersStore } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView" -import { PlaceholderBox, PlaceholderRaggedText, RandomNumberGenerator } from "lib/utils/placeholders" +import { + PlaceholderBox, + PlaceholderRaggedText, + RandomNumberGenerator, +} from "lib/utils/placeholders" import { Box, Flex, Sans, Spacer, Touchable } from "palette" import React from "react" import { StyleSheet, View } from "react-native" @@ -69,7 +73,11 @@ export const SaleArtworkGridItem: React.FC = ({ } const saleInfo = saleMessageOrBidInfo({ - artwork: { sale: saleArtwork.sale, saleArtwork, saleMessage: saleArtwork.artwork?.saleMessage || null }, + artwork: { + sale: saleArtwork.sale, + saleArtwork, + saleMessage: saleArtwork.artwork?.saleMessage || null, + }, }) return ( @@ -126,7 +134,9 @@ const styles = StyleSheet.create({ }, }) -export const SaleArtworkGridItemPlaceholder: React.FC<{ seed?: number }> = ({ seed = Math.random() }) => { +export const SaleArtworkGridItemPlaceholder: React.FC<{ seed?: number }> = ({ + seed = Math.random(), +}) => { const rng = new RandomNumberGenerator(seed) return ( diff --git a/src/lib/Components/ArtworkRail/ArtworkRailCard.tsx b/src/lib/Components/ArtworkRail/ArtworkRailCard.tsx index 7ef9a9ba264..463a3ef6c32 100644 --- a/src/lib/Components/ArtworkRail/ArtworkRailCard.tsx +++ b/src/lib/Components/ArtworkRail/ArtworkRailCard.tsx @@ -1,5 +1,8 @@ import { themeGet } from "@styled-system/theme-get" -import { ArtworkRailCard_artwork, ArtworkRailCard_artwork$key } from "__generated__/ArtworkRailCard_artwork.graphql" +import { + ArtworkRailCard_artwork, + ArtworkRailCard_artwork$key, +} from "__generated__/ArtworkRailCard_artwork.graphql" import { getUrgencyTag } from "lib/utils/getUrgencyTag" import { Flex, Sans, Text, useColor } from "palette" import React from "react" @@ -41,13 +44,20 @@ export const ArtworkRailCard: React.FC = ({ const { artistNames, date, partner, title, image } = artwork const saleMessage = saleMessageOrBidInfo({ artwork, isSmallTile: true }) - const urgencyTag = artwork?.sale?.isAuction && !artwork?.sale?.isClosed ? getUrgencyTag(artwork?.sale?.endAt) : null + const urgencyTag = + artwork?.sale?.isAuction && !artwork?.sale?.isClosed + ? getUrgencyTag(artwork?.sale?.endAt) + : null return ( - + {!!lotLabel && ( Lot {lotLabel} @@ -85,7 +95,11 @@ export interface ArtworkRailCardImageProps { urgencyTag?: string | null } -const ArtworkRailCardImage: React.FC = ({ image, size, urgencyTag = null }) => { +const ArtworkRailCardImage: React.FC = ({ + image, + size, + urgencyTag = null, +}) => { const color = useColor() const { width, height, src } = image?.resized || {} diff --git a/src/lib/Components/ArtworkRail/LargeArtworkRail.tsx b/src/lib/Components/ArtworkRail/LargeArtworkRail.tsx index 55ff09b48f5..632d896417f 100644 --- a/src/lib/Components/ArtworkRail/LargeArtworkRail.tsx +++ b/src/lib/Components/ArtworkRail/LargeArtworkRail.tsx @@ -1,5 +1,10 @@ import { LargeArtworkRail_artworks$key } from "__generated__/LargeArtworkRail_artworks.graphql" -import { PlaceholderBox, PlaceholderText, RandomWidthPlaceholderText, useMemoizedRandom } from "lib/utils/placeholders" +import { + PlaceholderBox, + PlaceholderText, + RandomWidthPlaceholderText, + useMemoizedRandom, +} from "lib/utils/placeholders" import { times } from "lodash" import { Flex, Join, Spacer } from "palette" import React from "react" @@ -8,7 +13,9 @@ import { graphql } from "relay-runtime" import { ArtworkRail, ArtworkRailProps } from "./ArtworkRail" import { ARTWORK_RAIL_CARD_IMAGE_HEIGHT } from "./ArtworkRailCard" -type LargeArtworkRailProps = Omit & { artworks: LargeArtworkRail_artworks$key } +type LargeArtworkRailProps = Omit & { + artworks: LargeArtworkRail_artworks$key +} const IMAGE_WIDTH = 295 diff --git a/src/lib/Components/ArtworkRail/SmallArtworkRail.tsx b/src/lib/Components/ArtworkRail/SmallArtworkRail.tsx index 5211fccdba3..750530b6a68 100644 --- a/src/lib/Components/ArtworkRail/SmallArtworkRail.tsx +++ b/src/lib/Components/ArtworkRail/SmallArtworkRail.tsx @@ -1,5 +1,10 @@ import { SmallArtworkRail_artworks$key } from "__generated__/SmallArtworkRail_artworks.graphql" -import { PlaceholderBox, PlaceholderText, RandomWidthPlaceholderText, useMemoizedRandom } from "lib/utils/placeholders" +import { + PlaceholderBox, + PlaceholderText, + RandomWidthPlaceholderText, + useMemoizedRandom, +} from "lib/utils/placeholders" import { times } from "lodash" import { Flex, Join, Spacer } from "palette" import React from "react" @@ -8,7 +13,9 @@ import { graphql } from "relay-runtime" import { ArtworkRail, ArtworkRailProps } from "./ArtworkRail" import { ARTWORK_RAIL_CARD_IMAGE_HEIGHT } from "./ArtworkRailCard" -type SmallArtworkRailProps = Omit & { artworks: SmallArtworkRail_artworks$key } +type SmallArtworkRailProps = Omit & { + artworks: SmallArtworkRail_artworks$key +} const IMAGE_WIDTH = 155 diff --git a/src/lib/Components/ArtworkTileRail/ArtworkTileRail.tsx b/src/lib/Components/ArtworkTileRail/ArtworkTileRail.tsx index 9a5a1f7f562..cb87dc151fa 100644 --- a/src/lib/Components/ArtworkTileRail/ArtworkTileRail.tsx +++ b/src/lib/Components/ArtworkTileRail/ArtworkTileRail.tsx @@ -47,7 +47,9 @@ export const ArtworkTileRailContainer: React.FC = { if (shouldTrack) { - tracking.trackEvent(tappedArtworkGroupThumbnail(contextModule!, item.internalID, item.slug)) + tracking.trackEvent( + tappedArtworkGroupThumbnail(contextModule!, item.internalID, item.slug) + ) } { !!onTilePress ? onTilePress(item.slug, item.internalID) : navigate(item.href!) @@ -66,7 +68,11 @@ export const ArtworkTileRailContainer: React.FC = ) } -export const tappedArtworkGroupThumbnail = (contextModule: Schema.ContextModules, internalID: string, slug: string) => { +export const tappedArtworkGroupThumbnail = ( + contextModule: Schema.ContextModules, + internalID: string, + slug: string +) => { return { action_name: Schema.ActionNames.TappedArtworkGroup, action_type: Schema.ActionTypes.Tap, diff --git a/src/lib/Components/ArtworkTileRail/ArtworkTileRailCard.tsx b/src/lib/Components/ArtworkTileRail/ArtworkTileRailCard.tsx index 919d742ba02..5b6a392c493 100644 --- a/src/lib/Components/ArtworkTileRail/ArtworkTileRailCard.tsx +++ b/src/lib/Components/ArtworkTileRail/ArtworkTileRailCard.tsx @@ -90,7 +90,12 @@ export const ArtworkTileRailCard: React.FC = ({ )} ) : ( - + ) const artistNamesDisplay = artistNames ? ( @@ -158,17 +163,20 @@ const ArtworkTileRailCardContainer: React.FC< ) } -export const ArtworkTileRailCardFragmentContainer = createFragmentContainer(ArtworkTileRailCardContainer, { - artwork: graphql` - fragment ArtworkTileRailCard_artwork on Artwork { - slug - internalID - href - artistNames - image { - imageURL +export const ArtworkTileRailCardFragmentContainer = createFragmentContainer( + ArtworkTileRailCardContainer, + { + artwork: graphql` + fragment ArtworkTileRailCard_artwork on Artwork { + slug + internalID + href + artistNames + image { + imageURL + } + saleMessage } - saleMessage - } - `, -}) + `, + } +) diff --git a/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tests.tsx b/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tests.tsx index 8e4b19dfb39..37a1ca17f72 100644 --- a/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tests.tsx +++ b/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tests.tsx @@ -5,21 +5,31 @@ import { AuctionResultsMidEstimate } from "./AuctionResultMidEstimate" describe("AuctionResultMidEstimate", () => { it("renders properly when the percentage is greater than 5", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(tree.root.findAllByType(IncreaseIcon).length).toEqual(1) expect(tree.root.findAllByType(Text)[0].props.color).toEqual("green100") }) it("renders properly when the percentage is less than -5", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(tree.root.findAllByType(DecreaseIcon).length).toEqual(1) expect(tree.root.findAllByType(Text)[0].props.color).toEqual("red100") }) it("renders properly when the percentage is between -5 and 5", () => { - const instance1 = renderWithWrappers() - const instance2 = renderWithWrappers() - const instance3 = renderWithWrappers() + const instance1 = renderWithWrappers( + + ) + const instance2 = renderWithWrappers( + + ) + const instance3 = renderWithWrappers( + + ) expect(instance1.root.findAllByType(Text)[0].props.color).toEqual("black60") expect(instance1.root.findAllByType(IncreaseIcon).length).toEqual(1) expect(instance1.root.findAllByType(IncreaseIcon)[0].props.fill).toEqual("black60") diff --git a/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tsx b/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tsx index 340579522ec..e07ba61e29e 100644 --- a/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tsx +++ b/src/lib/Components/AuctionResult/AuctionResultMidEstimate.tsx @@ -21,7 +21,11 @@ export const AuctionResultsMidEstimate: React.FC return ( {/* Up arrow is heavier toward bottom so appears off center without padding */} - {arrowDirection === "up" ? : } + {arrowDirection === "up" ? ( + + ) : ( + + )} {new Intl.NumberFormat().format(Number(value.replace(/%|-/gm, "")))}% {shortDescription} diff --git a/src/lib/Components/Bidding/BidFlow.tests.tsx b/src/lib/Components/Bidding/BidFlow.tests.tsx index 953096c1ee4..9cd16759823 100644 --- a/src/lib/Components/Bidding/BidFlow.tests.tsx +++ b/src/lib/Components/Bidding/BidFlow.tests.tsx @@ -62,7 +62,9 @@ it("allows bidders with a qualified credit card to bid", async () => { screen = fakeNavigator.nextStep() expect(extractText(screen.root)).toContain("Confirm your bid") - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder)) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.highestBidder) + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 relay.commitMutation = commitMutationMock((_, { onCompleted }) => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -99,10 +101,18 @@ it("allows bidders without a qualified credit card to register a card and bid", stripe.createTokenWithCard.mockReturnValueOnce(stripeToken) relay.commitMutation = jest .fn() - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.updateMyUserProfile)) - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.creatingCreditCardSuccess)) - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.placingBid.bidAccepted)) - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder)) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.updateMyUserProfile) + ) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.creatingCreditCardSuccess) + ) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.placingBid.bidAccepted) + ) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.highestBidder) + ) // manually setting state to avoid duplicating tests for skipping UI interaction, but practically better not to do this. screen.root.findByProps({ nextScreen: true }).instance.setState({ diff --git a/src/lib/Components/Bidding/Components/Icon.tsx b/src/lib/Components/Bidding/Components/Icon.tsx index 5521cebc553..a6c1db54483 100644 --- a/src/lib/Components/Bidding/Components/Icon.tsx +++ b/src/lib/Components/Bidding/Components/Icon.tsx @@ -1,4 +1,6 @@ import React from "react" import { Image } from "../Elements/Image" -export const Icon20 = (props: any /* STRICTNESS_MIGRATION */) => +export const Icon20 = (props: any /* STRICTNESS_MIGRATION */) => ( + +) diff --git a/src/lib/Components/Bidding/Components/PaymentInfo.tests.tsx b/src/lib/Components/Bidding/Components/PaymentInfo.tests.tsx index c584b9be17c..9ab24cbe426 100644 --- a/src/lib/Components/Bidding/Components/PaymentInfo.tests.tsx +++ b/src/lib/Components/Bidding/Components/PaymentInfo.tests.tsx @@ -25,16 +25,22 @@ it("renders without throwing an error", () => { }) it("shows the billing address that the user typed in the billing address form", () => { - const billingAddressRow = renderWithWrappers().root.findAllByType(BidInfoRow)[1] + const billingAddressRow = renderWithWrappers( + + ).root.findAllByType(BidInfoRow)[1] billingAddressRow.instance.props.onPress() // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 expect(nextStep.component).toEqual(BillingAddress) - expect(billingAddressRow.findAllByType(Text)[1].props.children).toEqual("401 Broadway 25th floor New York NY") + expect(billingAddressRow.findAllByType(Text)[1].props.children).toEqual( + "401 Broadway 25th floor New York NY" + ) }) it("shows the cc info that the user had typed into the form", () => { - const creditCardRow = renderWithWrappers().root.findAllByType(BidInfoRow)[0] + const creditCardRow = renderWithWrappers().root.findAllByType( + BidInfoRow + )[0] creditCardRow.instance.props.onPress() // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 expect(nextStep.component).toEqual(CreditCardForm) diff --git a/src/lib/Components/Bidding/Components/PaymentInfo.tsx b/src/lib/Components/Bidding/Components/PaymentInfo.tsx index 83a602718ae..066f3ada27e 100644 --- a/src/lib/Components/Bidding/Components/PaymentInfo.tsx +++ b/src/lib/Components/Bidding/Components/PaymentInfo.tsx @@ -96,6 +96,8 @@ export class PaymentInfo extends React.Component { } private formatAddress(address: Address) { - return [address.addressLine1, address.addressLine2, address.city, address.state].filter((el) => el).join(" ") + return [address.addressLine1, address.addressLine2, address.city, address.state] + .filter((el) => el) + .join(" ") } } diff --git a/src/lib/Components/Bidding/Components/Timer.tests.tsx b/src/lib/Components/Bidding/Components/Timer.tests.tsx index 0478e8241b9..aa736ed8985 100644 --- a/src/lib/Components/Bidding/Components/Timer.tests.tsx +++ b/src/lib/Components/Bidding/Components/Timer.tests.tsx @@ -80,7 +80,11 @@ it("shows 'Live' when the liveStartsAt prop is given", () => { it("shows 'Starts' the sale has not started yet", () => { const timer = renderWithWrappers( - + ) expect(getTimerLabel(timer)).toContain("Starts") @@ -88,7 +92,12 @@ it("shows 'Starts' the sale has not started yet", () => { it("shows 'Bidding closed' when the auction is closed", () => { const timer = renderWithWrappers( - + ) expect(getTimerLabel(timer)).toContain("Bidding closed") diff --git a/src/lib/Components/Bidding/Components/Timer.tsx b/src/lib/Components/Bidding/Components/Timer.tsx index 70f80fb1379..e12cf923fc4 100644 --- a/src/lib/Components/Bidding/Components/Timer.tsx +++ b/src/lib/Components/Bidding/Components/Timer.tsx @@ -33,7 +33,10 @@ function formatDate(date: string) { return dateInMoment.format(format) } -export function relevantStateData(currentState: AuctionTimerState, { liveStartsAt, startsAt, endsAt }: Props) { +export function relevantStateData( + currentState: AuctionTimerState, + { liveStartsAt, startsAt, endsAt }: Props +) { switch (currentState) { case AuctionTimerState.PREVIEW: { if (!startsAt) { diff --git a/src/lib/Components/Bidding/Context/TimeOffsetProvider.tsx b/src/lib/Components/Bidding/Context/TimeOffsetProvider.tsx index 5c352ecae62..b22f5084291 100644 --- a/src/lib/Components/Bidding/Context/TimeOffsetProvider.tsx +++ b/src/lib/Components/Bidding/Context/TimeOffsetProvider.tsx @@ -33,7 +33,8 @@ const getGravityTimestampInMilliSeconds = async () => { const system = systemTimeResponse?.system const possibleNetworkLatencyInMilliSeconds = (getLocalTimestampInMilliSeconds() - startTime) / 2 - const serverTimestampInMilliSeconds = (system?.time?.unix || 0) * 1e3 + possibleNetworkLatencyInMilliSeconds + const serverTimestampInMilliSeconds = + (system?.time?.unix || 0) * 1e3 + possibleNetworkLatencyInMilliSeconds if (__DEV__) { if (typeof jest === "undefined") { diff --git a/src/lib/Components/Bidding/Elements/types.d.ts b/src/lib/Components/Bidding/Elements/types.d.ts index cbd602a5ba7..77e46e3e41c 100644 --- a/src/lib/Components/Bidding/Elements/types.d.ts +++ b/src/lib/Components/Bidding/Elements/types.d.ts @@ -61,7 +61,15 @@ export interface ColorProps { export function color(...args: any[]): any // text align -export type TextAlignValue = "left" | "right" | "center" | "justify" | "justify-all" | "start" | "end" | "match-parent" +export type TextAlignValue = + | "left" + | "right" + | "center" + | "justify" + | "justify-all" + | "start" + | "end" + | "match-parent" export type ResponsiveTextAlignValue = ResponsiveValue export interface TextAlignProps { diff --git a/src/lib/Components/Bidding/Screens/BidResult.tests.tsx b/src/lib/Components/Bidding/Screens/BidResult.tests.tsx index b34e01fe166..f69c82e21fd 100644 --- a/src/lib/Components/Bidding/Screens/BidResult.tests.tsx +++ b/src/lib/Components/Bidding/Screens/BidResult.tests.tsx @@ -190,7 +190,9 @@ describe("BidResult component", () => { bidResult.root.findByType(Button).props.onPress() jest.runAllTicks() - expect(navigate).toHaveBeenCalledWith("https://live-staging.artsy.net/sale-id", { modal: true }) + expect(navigate).toHaveBeenCalledWith("https://live-staging.artsy.net/sale-id", { + modal: true, + }) }) }) }) diff --git a/src/lib/Components/Bidding/Screens/BidResult.tsx b/src/lib/Components/Bidding/Screens/BidResult.tsx index edd56139afd..b47066a3033 100644 --- a/src/lib/Components/Bidding/Screens/BidResult.tsx +++ b/src/lib/Components/Bidding/Screens/BidResult.tsx @@ -47,7 +47,10 @@ export class BidResult extends React.Component { backButtonListener?: NativeEventSubscription = undefined componentDidMount = () => { - this.backButtonListener = BackHandler.addEventListener("hardwareBackPress", this.handleBackButton) + this.backButtonListener = BackHandler.addEventListener( + "hardwareBackPress", + this.handleBackButton + ) } componentWillUnmount = () => { @@ -111,14 +114,20 @@ export class BidResult extends React.Component { } /> - {status === "PENDING" ? messageForPollingTimeout.title : message_header || "You’re the highest bidder"} + {status === "PENDING" + ? messageForPollingTimeout.title + : message_header || "You’re the highest bidder"} {status !== "WINNING" && ( - {status === "PENDING" ? messageForPollingTimeout.description : message_description_md} + {status === "PENDING" + ? messageForPollingTimeout.description + : message_description_md} )} - {!!this.shouldDisplayTimer(status) && } + {!!this.shouldDisplayTimer(status) && ( + + )} {this.canBidAgain(status) ? ( diff --git a/src/lib/Components/Bidding/Screens/BillingAddress.tests.tsx b/src/lib/Components/Bidding/Screens/BillingAddress.tests.tsx index 1f524d9794c..1e8e71fcb6b 100644 --- a/src/lib/Components/Bidding/Screens/BillingAddress.tests.tsx +++ b/src/lib/Components/Bidding/Screens/BillingAddress.tests.tsx @@ -50,7 +50,11 @@ describe("BillingAddress component", () => { it("correctly populates relevant inputs with the passed address fields", () => { const { getByTestId } = renderWithWrappersTL( - + ) expect(getByTestId("input-full-name").props.value).toEqual(mockFullAddress.fullName) @@ -64,7 +68,11 @@ describe("BillingAddress component", () => { it("fires the passed callback when address is submitted and no required field is missing", () => { const { getByTestId } = renderWithWrappersTL( - + ) getByTestId("button-add").props.onClick() diff --git a/src/lib/Components/Bidding/Screens/BillingAddress.tsx b/src/lib/Components/Bidding/Screens/BillingAddress.tsx index a531fa520a8..e5c3ea95aff 100644 --- a/src/lib/Components/Bidding/Screens/BillingAddress.tsx +++ b/src/lib/Components/Bidding/Screens/BillingAddress.tsx @@ -23,7 +23,11 @@ screenTrack({ context_screen_owner_type: null, }) -export const BillingAddress: React.FC = ({ onSubmit, navigator, billingAddress }) => { +export const BillingAddress: React.FC = ({ + onSubmit, + navigator, + billingAddress, +}) => { const scrollViewRef = useRef(null) const fullNameRef = useRef(null) @@ -105,7 +109,9 @@ export const BillingAddress: React.FC = ({ onSubmit, naviga return ( - navigator?.pop()}>Add billing address + navigator?.pop()}> + Add billing address + (nextStep = route) } jest.useFakeTimers() -const mockPostNotificationName = LegacyNativeModules.ARNotificationsManager.postNotificationName as jest.Mock +const mockPostNotificationName = LegacyNativeModules.ARNotificationsManager + .postNotificationName as jest.Mock // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 const findPlaceBidButton = (component) => { @@ -164,7 +165,11 @@ describe("checkbox and payment info display", () => { expect(component.root.findAllByType(BidInfoRow).length).toEqual(1) const serifs = component.root.findAllByType(Serif) - expect(serifs.find((s) => s.props.children.join && s.props.children.join("").includes("You agree to"))).toBeTruthy() + expect( + serifs.find( + (s) => s.props.children.join && s.props.children.join("").includes("You agree to") + ) + ).toBeTruthy() }) it("shows a checkbox but no payment info if the user is not registered and has cc on file", () => { @@ -246,7 +251,9 @@ describe("when pressing bid button", () => { const component = mountConfirmBidComponent(initialProps) component.root.findByType(Checkbox).props.onPress() - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder)) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.highestBidder) + ) relay.commitMutation = jest.fn() findPlaceBidButton(component).props.onPress() @@ -306,7 +313,8 @@ describe("when pressing bid button", () => { it("displays an error message on a createBidderPosition mutation failure", async () => { const error = { - message: 'GraphQL Timeout Error: Mutation.createBidderPosition has timed out after waiting for 5000ms"}', + message: + 'GraphQL Timeout Error: Mutation.createBidderPosition has timed out after waiting for 5000ms"}', } // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -348,10 +356,18 @@ describe("editing bid amount", () => { ...initialPropsForRegisteredUser, navigator: fakeNavigator, } - fakeNavigator.push({ component: SelectMaxBid, id: "", title: "", passProps: fakeNavigatorProps }) + fakeNavigator.push({ + component: SelectMaxBid, + id: "", + title: "", + passProps: fakeNavigatorProps, + }) fakeNavigator.push({ component: ConfirmBid, id: "", title: "", passProps: fakeNavigatorProps }) - const component = mountConfirmBidComponent({ ...initialPropsForRegisteredUser, navigator: fakeNavigator }) + const component = mountConfirmBidComponent({ + ...initialPropsForRegisteredUser, + navigator: fakeNavigator, + }) const selectMaxBidRow = component.root.findAllByType(TouchableWithoutFeedback)[0] @@ -412,7 +428,9 @@ describe("polling to verify bid position", () => { const component = mountConfirmBidComponent(initialProps) component.root.findByType(Checkbox).props.onPress() - bidderPositionQueryMock.mockReturnValue(Promise.resolve(mockRequestResponses.pollingForBid.pending)) + bidderPositionQueryMock.mockReturnValue( + Promise.resolve(mockRequestResponses.pollingForBid.pending) + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 relay.commitMutation = commitMutationMock((_, { onCompleted }) => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -439,7 +457,9 @@ describe("polling to verify bid position", () => { const component = mountConfirmBidComponent(initialProps) component.root.findByType(Checkbox).props.onPress() - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder)) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.highestBidder) + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 relay.commitMutation = commitMutationMock((_, { onCompleted }) => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -466,7 +486,9 @@ describe("polling to verify bid position", () => { const component = mountConfirmBidComponent(initialProps) component.root.findByType(Checkbox).props.onPress() - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.outbid)) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.outbid) + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 relay.commitMutation = commitMutationMock((_, { onCompleted }) => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -493,7 +515,9 @@ describe("polling to verify bid position", () => { const component = mountConfirmBidComponent(initialProps) component.root.findByType(Checkbox).props.onPress() - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.reserveNotMet)) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.reserveNotMet) + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 relay.commitMutation = commitMutationMock((_, { onCompleted }) => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -524,7 +548,9 @@ describe("polling to verify bid position", () => { refreshSaleArtwork: jest.fn(), }) component.root.findByType(Checkbox).props.onPress() - bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.reserveNotMet)) + bidderPositionQueryMock.mockReturnValueOnce( + Promise.resolve(mockRequestResponses.pollingForBid.reserveNotMet) + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 relay.commitMutation = commitMutationMock((_, { onCompleted }) => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -607,8 +633,9 @@ describe("polling to verify bid position", () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 expect(nextStep.passProps).toEqual( expect.objectContaining({ - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - bidderPositionResult: mockRequestResponses.placingBid.bidRejected.createBidderPosition.result, + bidderPositionResult: + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + mockRequestResponses.placingBid.bidRejected.createBidderPosition.result, }) ) }) @@ -628,8 +655,9 @@ describe("ConfirmBid for unqualified user", () => { } it("shows the billing address that the user typed in the billing address form", () => { - const billingAddressRow = - mountConfirmBidComponent(initialPropsForUnqualifiedUser).root.findAllByType(TouchableWithoutFeedback)[2] + const billingAddressRow = mountConfirmBidComponent( + initialPropsForUnqualifiedUser + ).root.findAllByType(TouchableWithoutFeedback)[2] billingAddressRow.instance.props.onPress() @@ -639,12 +667,15 @@ describe("ConfirmBid for unqualified user", () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 nextStep.passProps.onSubmit(billingAddress) - expect(billingAddressRow.findAllByType(Text)[1].props.children).toEqual("401 Broadway 25th floor New York NY") + expect(billingAddressRow.findAllByType(Text)[1].props.children).toEqual( + "401 Broadway 25th floor New York NY" + ) }) it("shows the credit card form when the user tap the edit text in the credit card row", () => { - const creditcardRow = - mountConfirmBidComponent(initialPropsForUnqualifiedUser).root.findAllByType(TouchableWithoutFeedback)[1] + const creditcardRow = mountConfirmBidComponent( + initialPropsForUnqualifiedUser + ).root.findAllByType(TouchableWithoutFeedback)[1] creditcardRow.instance.props.onPress() @@ -767,7 +798,8 @@ describe("ConfirmBid for unqualified user", () => { expect.objectContaining({ bidderPositionResult: { message_header: "An error occurred", - message_description_md: "Your bid couldn’t be placed. Please\ncheck your internet connection\nand try again.", + message_description_md: + "Your bid couldn’t be placed. Please\ncheck your internet connection\nand try again.", }, }) ) @@ -778,9 +810,15 @@ describe("ConfirmBid for unqualified user", () => { stripe.createTokenWithCard.mockReturnValueOnce(stripeToken) relay.commitMutation = jest .fn() - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.updateMyUserProfile)) - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.creatingCreditCardSuccess)) - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.placingBid.bidAccepted)) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.updateMyUserProfile) + ) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.creatingCreditCardSuccess) + ) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.placingBid.bidAccepted) + ) }) it("commits two mutations, createCreditCard followed by createBidderPosition on a successful bid", async () => { diff --git a/src/lib/Components/Bidding/Screens/ConfirmBid/index.tsx b/src/lib/Components/Bidding/Screens/ConfirmBid/index.tsx index 139600e5eb6..47cfcfba627 100644 --- a/src/lib/Components/Bidding/Screens/ConfirmBid/index.tsx +++ b/src/lib/Components/Bidding/Screens/ConfirmBid/index.tsx @@ -66,7 +66,8 @@ const MAX_POLL_ATTEMPTS = 20 const resultForNetworkError = { message_header: "An error occurred", - message_description_md: "Your bid couldn’t be placed. Please\ncheck your internet connection\nand try again.", + message_description_md: + "Your bid couldn’t be placed. Please\ncheck your internet connection\nand try again.", } @screenTrack({ @@ -212,7 +213,8 @@ export class ConfirmBid extends React.Component(this.props.relay.environment, { onCompleted: (results, errors) => { - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - return isEmpty(errors) ? this.verifyBidderPosition(results) : this.presentErrorResult(errors) + return isEmpty(errors) + ? this.verifyBidderPosition(results) + : // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + this.presentErrorResult(errors) }, onError: this.presentErrorResult.bind(this), mutation: graphql` @@ -409,10 +413,13 @@ export class ConfirmBid extends React.Component - this.props.navigator?.pop()}>Confirm your bid + this.props.navigator?.pop()}> + Confirm your bid + @@ -472,8 +482,12 @@ export class ConfirmBid extends React.Component {!!artworkImage && ( - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - + )} @@ -486,7 +500,14 @@ export class ConfirmBid extends React.Component - + { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 artwork.title @@ -552,7 +573,9 @@ export class ConfirmBid extends React.Component You agree to{" "} - this.onConditionsOfSaleLinkPressed()}> + this.onConditionsOfSaleLinkPressed()} + > {partnerName(sale!)} Conditions of Sale . @@ -562,7 +585,9 @@ export class ConfirmBid extends React.Component You agree to{" "} - this.onConditionsOfSaleLinkPressed()}> + this.onConditionsOfSaleLinkPressed()} + > {partnerName(sale!)} Conditions of Sale . @@ -590,7 +615,10 @@ export class ConfirmBid extends React.Component, hasQualifiedCreditCards: boolean) { + private determineDisplayRequirements( + bidders: ReadonlyArray, + hasQualifiedCreditCards: boolean + ) { const isRegistered = bidders && bidders.length > 0 const requiresCheckbox = !isRegistered const requiresPaymentInformation = !(isRegistered || hasQualifiedCreditCards) diff --git a/src/lib/Components/Bidding/Screens/CreditCardForm.tests.tsx b/src/lib/Components/Bidding/Screens/CreditCardForm.tests.tsx index 839a95b9961..b2bba7b9f67 100644 --- a/src/lib/Components/Bidding/Screens/CreditCardForm.tests.tsx +++ b/src/lib/Components/Bidding/Screens/CreditCardForm.tests.tsx @@ -110,7 +110,9 @@ it("shows an error when stripe's API returns an error", () => { component.findByType(Button).props.onPress() jest.runAllTicks() - expect(component.findAllByType(Sans)[0].props.children).toEqual("There was an error. Please try again.") + expect(component.findAllByType(Sans)[0].props.children).toEqual( + "There was an error. Please try again." + ) }) const creditCard = { diff --git a/src/lib/Components/Bidding/Screens/CreditCardForm.tsx b/src/lib/Components/Bidding/Screens/CreditCardForm.tsx index 166e068a686..4259671de8e 100644 --- a/src/lib/Components/Bidding/Screens/CreditCardForm.tsx +++ b/src/lib/Components/Bidding/Screens/CreditCardForm.tsx @@ -93,7 +93,9 @@ export class CreditCardForm extends Component - this.props.navigator?.pop()}>Add credit card + this.props.navigator?.pop()}> + Add credit card + @@ -123,8 +125,8 @@ export class CreditCardForm extends Component Registration is free. - {"\n"}A credit card is required to bid. Artsy will never charge this card without your permission, and - you are not required to use this card to pay if you win. + {"\n"}A credit card is required to bid. Artsy will never charge this card without + your permission, and you are not required to use this card to pay if you win. diff --git a/src/lib/Components/Bidding/Screens/Registration.tests.tsx b/src/lib/Components/Bidding/Screens/Registration.tests.tsx index c5946e4ef09..1c6350a2d68 100644 --- a/src/lib/Components/Bidding/Screens/Registration.tests.tsx +++ b/src/lib/Components/Bidding/Screens/Registration.tests.tsx @@ -1,6 +1,9 @@ import { Registration_me } from "__generated__/Registration_me.graphql" import { Registration_sale } from "__generated__/Registration_sale.graphql" -import { RegistrationResult, RegistrationStatus } from "lib/Components/Bidding/Screens/RegistrationResult" +import { + RegistrationResult, + RegistrationStatus, +} from "lib/Components/Bidding/Screens/RegistrationResult" import { Modal } from "lib/Components/Modal" import { LinkText } from "lib/Components/Text/LinkText" import { LegacyNativeModules } from "lib/NativeModules/LegacyNativeModules" @@ -44,7 +47,9 @@ beforeEach(() => { it("renders properly for a user without a credit card", () => { const component = renderWithWrappers() - expect(component.root.findAllByType(Text)[5].props.children).toEqual("A valid credit card is required.") + expect(component.root.findAllByType(Text)[5].props.children).toEqual( + "A valid credit card is required." + ) }) it("renders properly for a user with a credit card", () => { @@ -81,7 +86,9 @@ it("shows the billing address that the user typed in the billing address form", nextStep.passProps.onSubmit(billingAddress) - expect(billingAddressRow.findAllByType(Text)[1].props.children).toEqual("401 Broadway 25th floor New York NY") + expect(billingAddressRow.findAllByType(Text)[1].props.children).toEqual( + "401 Broadway 25th floor New York NY" + ) }) it("shows the credit card form when the user tap the edit text in the credit card row", () => { @@ -161,9 +168,11 @@ describe("when pressing register button", () => { stripe.createTokenWithCard.mockReturnValueOnce(stripeToken) const component = renderWithWrappers() - component.root - .findByType(Registration) - .instance.setState({ conditionsOfSaleChecked: true, billingAddress, creditCardToken: stripeToken }) + component.root.findByType(Registration).instance.setState({ + conditionsOfSaleChecked: true, + billingAddress, + creditCardToken: stripeToken, + }) await component.root.findAllByType(Button)[1].props.onPress() expect(relay.commitMutation).toHaveBeenCalledWith( @@ -253,7 +262,9 @@ describe("when pressing register button", () => { relay.commitMutation = jest .fn() - .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.updateMyUserProfile)) + .mockImplementationOnce((_, { onCompleted }) => + onCompleted(mockRequestResponses.updateMyUserProfile) + ) stripe.createTokenWithCard.mockImplementation(() => { throw new Error("Error tokenizing card") @@ -465,7 +476,9 @@ describe("when pressing register button", () => { } console.error = jest.fn() // Silences component logging. - relay.commitMutation = jest.fn().mockImplementation((_, { onCompleted }) => onCompleted({}, [error])) + relay.commitMutation = jest + .fn() + .mockImplementation((_, { onCompleted }) => onCompleted({}, [error])) const component = renderWithWrappers() diff --git a/src/lib/Components/Bidding/Screens/Registration.tsx b/src/lib/Components/Bidding/Screens/Registration.tsx index 466b9c8383a..5ddaa94191d 100644 --- a/src/lib/Components/Bidding/Screens/Registration.tsx +++ b/src/lib/Components/Bidding/Screens/Registration.tsx @@ -19,7 +19,13 @@ import { Box, Button, Flex, Text } from "palette" import { Checkbox } from "palette/elements/Checkbox" import React from "react" import { ScrollView, View, ViewProps } from "react-native" -import { commitMutation, createFragmentContainer, graphql, QueryRenderer, RelayProp } from "react-relay" +import { + commitMutation, + createFragmentContainer, + graphql, + QueryRenderer, + RelayProp, +} from "react-relay" // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 import stripe from "tipsi-stripe" import { LinkText } from "../../Text/LinkText" @@ -107,7 +113,9 @@ export class Registration extends React.Component(this.props.relay.environment, { onCompleted: (results, errors) => - isEmpty(errors) ? this.presentRegistrationSuccess(results) : this.presentErrorModal(errors, null), + isEmpty(errors) + ? this.presentRegistrationSuccess(results) + : this.presentErrorModal(errors, null), onError: (error) => this.presentErrorModal(error, null), mutation: graphql` mutation RegistrationCreateBidderMutation($input: CreateBidderInput!) { @@ -260,9 +271,12 @@ export class Registration extends React.Component This auction requires Artsy to verify your identity before bidding. - After you register, you’ll receive an email with a link to complete identity verification. + + After you register, you’ll receive an email with a link to complete identity + verification. + ) } { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 !requiresPaymentInformation && !bidderNeedsIdentityVerification({ sale, user: me }) && ( - To complete your registration, please confirm that you agree to the Conditions of Sale. + + To complete your registration, please confirm that you agree to the Conditions of + Sale. + ) } this.conditionsOfSalePressed()} disabled={isLoading}> Agree to{" "} - Conditions of Sale + + Conditions of Sale + diff --git a/src/lib/Components/Bidding/Screens/RegistrationResult.tests.tsx b/src/lib/Components/Bidding/Screens/RegistrationResult.tests.tsx index 0277190be03..a1644c289ab 100644 --- a/src/lib/Components/Bidding/Screens/RegistrationResult.tests.tsx +++ b/src/lib/Components/Bidding/Screens/RegistrationResult.tests.tsx @@ -15,40 +15,56 @@ import { Icon20 } from "../Components/Icon" describe("Registration result component", () => { it("renders registration pending properly", () => { const tree = renderWithWrappers( - + ) expect(extractText(tree.root)).toMatch("Registration pending") expect(extractText(tree.root)).toMatch( "Artsy is reviewing your registration and you will receive an email when it has been confirmed. Please email " ) - expect(extractText(tree.root)).not.toMatch("This auction requires Artsy to verify your identity before bidding.") + expect(extractText(tree.root)).not.toMatch( + "This auction requires Artsy to verify your identity before bidding." + ) }) it("renders registration pending with an explanation about IDV", () => { const tree = renderWithWrappers( - + ) expect(extractText(tree.root)).toMatch("Registration pending") - expect(extractText(tree.root)).toMatch("This auction requires Artsy to verify your identity before bidding.") + expect(extractText(tree.root)).toMatch( + "This auction requires Artsy to verify your identity before bidding." + ) expect(extractText(tree.root)).not.toMatch( "Artsy is reviewing your registration and you will receive an email when it has been confirmed. Please email " ) }) it("does not render the icon when the registration status is pending", () => { - const component = renderWithWrappers() + const component = renderWithWrappers( + + ) expect(component.root.findAllByType(Icon20).length).toEqual(0) }) it("renders registration complete properly", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(extractText(tree.root)).toMatch("Registration complete") }) it("renders registration error properly", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(extractText(tree.root)).toMatch("An error occurred") expect(extractText(tree.root)).toMatch("Please contact") @@ -56,7 +72,9 @@ describe("Registration result component", () => { }) it("renders an error screen when the status is a network error", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(extractText(tree.root)).toMatch("An error occurred") expect(extractText(tree.root)).toMatch("Please\ncheck your internet connection\nand try again.") @@ -66,14 +84,18 @@ describe("Registration result component", () => { Linking.canOpenURL = jest.fn().mockReturnValue(Promise.resolve(true)) Linking.openURL = jest.fn() - const component = renderWithWrappers() + const component = renderWithWrappers( + + ) await component.root.findByType(LinkText).props.onPress() expect(Linking.openURL).toBeCalledWith("mailto:support@artsy.net") }) it("dismisses the controller when the continue button is pressed", () => { jest.useFakeTimers() - const component = renderWithWrappers() + const component = renderWithWrappers( + + ) component.root.findByType(Button).props.onPress() jest.runAllTicks() diff --git a/src/lib/Components/Bidding/Screens/RegistrationResult.tsx b/src/lib/Components/Bidding/Screens/RegistrationResult.tsx index ded39e099eb..7efcb7f626b 100644 --- a/src/lib/Components/Bidding/Screens/RegistrationResult.tsx +++ b/src/lib/Components/Bidding/Screens/RegistrationResult.tsx @@ -58,7 +58,8 @@ const registrationPendingDueToUnverifiedStatusMessage = { const registrationErrorMessage = { title: "An error occurred", - description: "Please contact [support@artsy.net](mailto:support@artsy.net)\n" + "with any questions.", + description: + "Please contact [support@artsy.net](mailto:support@artsy.net)\n" + "with any questions.", } const registrationNetworkErrorMessage = { @@ -108,7 +109,10 @@ export class RegistrationResult extends React.Component backButtonListener?: NativeEventSubscription = undefined componentDidMount = () => { - this.backButtonListener = BackHandler.addEventListener("hardwareBackPress", this.handleBackButton) + this.backButtonListener = BackHandler.addEventListener( + "hardwareBackPress", + this.handleBackButton + ) } componentWillUnmount = () => { @@ -163,7 +167,9 @@ export class RegistrationResult extends React.Component - {status !== RegistrationStatus.RegistrationStatusPending && } + {status !== RegistrationStatus.RegistrationStatusPending && ( + + )} {title} @@ -172,7 +178,9 @@ export class RegistrationResult extends React.Component diff --git a/src/lib/Components/Bidding/Screens/SelectMaxBid.tests.tsx b/src/lib/Components/Bidding/Screens/SelectMaxBid.tests.tsx index a0c1f16eb3b..74023880ce6 100644 --- a/src/lib/Components/Bidding/Screens/SelectMaxBid.tests.tsx +++ b/src/lib/Components/Bidding/Screens/SelectMaxBid.tests.tsx @@ -76,13 +76,23 @@ beforeEach(() => { it("renders without throwing an error", () => { renderWithWrappers( - + ) }) it("shows a spinner while fetching new bid increments", () => { const component = renderWithWrappers( - + ) const selectBidComponent = component.root.findByType(SelectMaxBid) @@ -93,22 +103,37 @@ it("shows a spinner while fetching new bid increments", () => { it("refetches in next component's refreshSaleArtwork", () => { const component = renderWithWrappers( - + ) component.root.findByType(Button).props.onPress() const nextScreen = fakeNavigator.nextStep() nextScreen.root.findByProps({ nextScreen: true }).instance.props.refreshSaleArtwork() - expect(fakeRelay.refetch).toHaveBeenCalledWith({ saleArtworkNodeID: "sale-artwork-id" }, null, expect.anything(), { - force: true, - }) + expect(fakeRelay.refetch).toHaveBeenCalledWith( + { saleArtworkNodeID: "sale-artwork-id" }, + null, + expect.anything(), + { + force: true, + } + ) expect(component.root.findByType(ActivityIndicator)).toBeDefined() }) it("removes the spinner once the refetch is complete", () => { const component = renderWithWrappers( - + ) component.root.findByType(Button).props.onPress() const nextScreen = fakeNavigator.nextStep() diff --git a/src/lib/Components/Bidding/Screens/SelectMaxBid.tsx b/src/lib/Components/Bidding/Screens/SelectMaxBid.tsx index acc6039a2db..56556b79b9a 100644 --- a/src/lib/Components/Bidding/Screens/SelectMaxBid.tsx +++ b/src/lib/Components/Bidding/Screens/SelectMaxBid.tsx @@ -158,7 +158,11 @@ export const SelectMaxBidQueryRenderer: React.FC<{ saleID, }} render={renderWithLoadProgress((props) => ( - + ))} /> diff --git a/src/lib/Components/Bidding/Validators/validateAddressFieldsPresence.tests.ts b/src/lib/Components/Bidding/Validators/validateAddressFieldsPresence.tests.ts index ad32c8cfeb6..1357bcbc63a 100644 --- a/src/lib/Components/Bidding/Validators/validateAddressFieldsPresence.tests.ts +++ b/src/lib/Components/Bidding/Validators/validateAddressFieldsPresence.tests.ts @@ -7,6 +7,10 @@ describe("Presence validator", () => { }) it("correctly returns missing fields' keys as string[]", () => { - expect(validateAddressFieldsPresence(mockPartiallyEmptyAddress)).toEqual(["fullName", "state", "country"]) + expect(validateAddressFieldsPresence(mockPartiallyEmptyAddress)).toEqual([ + "fullName", + "state", + "country", + ]) }) }) diff --git a/src/lib/Components/Buttons/DarkNavigationButton.tsx b/src/lib/Components/Buttons/DarkNavigationButton.tsx index 29b28a8777c..ce5cd1d77da 100644 --- a/src/lib/Components/Buttons/DarkNavigationButton.tsx +++ b/src/lib/Components/Buttons/DarkNavigationButton.tsx @@ -21,7 +21,9 @@ export default class DarkNavigationButton extends React.Component { {this.props.title} - {!!showNavArrow && } + {!!showNavArrow && ( + + )} diff --git a/src/lib/Components/Buttons/InfoButton.tests.tsx b/src/lib/Components/Buttons/InfoButton.tests.tsx index 47b3e1bc3ee..ba08551f014 100644 --- a/src/lib/Components/Buttons/InfoButton.tests.tsx +++ b/src/lib/Components/Buttons/InfoButton.tests.tsx @@ -21,7 +21,11 @@ describe("InfoButton", () => { it("only shows the modal when the button is pressed", () => { const wrapper = renderWithWrappers( - Hello} /> + Hello} + /> ) expect(wrapper.root.findByType(FancyModal).props.visible).toBe(false) wrapper.root.findByType(TouchableOpacity).props.onPress() @@ -31,7 +35,12 @@ describe("InfoButton", () => { it("calls onPress arg if it's passed in", () => { const handlePress = jest.fn() const wrapper = renderWithWrappers( - Hello} onPress={handlePress} /> + Hello} + onPress={handlePress} + /> ) wrapper.root.findByType(TouchableOpacity).props.onPress() diff --git a/src/lib/Components/Buttons/InfoButton.tsx b/src/lib/Components/Buttons/InfoButton.tsx index 3906abb127c..0c22fff8f3a 100644 --- a/src/lib/Components/Buttons/InfoButton.tsx +++ b/src/lib/Components/Buttons/InfoButton.tsx @@ -50,7 +50,11 @@ export const InfoButton: React.FC = ({ {!!subTitle && {subTitle}} - setModalVisible(false)}> + setModalVisible(false)} + > setModalVisible(false)}> {modalTitle ?? title} diff --git a/src/lib/Components/Countdown/CountdownTimer.tests.tsx b/src/lib/Components/Countdown/CountdownTimer.tests.tsx index 0ab0c856161..1f42d01b8d1 100644 --- a/src/lib/Components/Countdown/CountdownTimer.tests.tsx +++ b/src/lib/Components/Countdown/CountdownTimer.tests.tsx @@ -1,6 +1,8 @@ // Mock moment to always give back a formatted time string jest.mock("moment-timezone", () => { - const momentMock: any = jest.fn(() => ({ format: (format: string) => (format.length > 3 ? "Mon" : "7pm") })) + const momentMock: any = jest.fn(() => ({ + format: (format: string) => (format.length > 3 ? "Mon" : "7pm"), + })) momentMock.duration = jest.requireActual("moment-timezone").duration return momentMock }) diff --git a/src/lib/Components/Countdown/DurationProvider.tests.tsx b/src/lib/Components/Countdown/DurationProvider.tests.tsx index f70a5e069c3..25ef560a068 100644 --- a/src/lib/Components/Countdown/DurationProvider.tests.tsx +++ b/src/lib/Components/Countdown/DurationProvider.tests.tsx @@ -20,7 +20,9 @@ describe("DurationProvider", () => { ) - expect(comp.find(DurationConsumer).props().duration.toString()).toEqual(moment.duration(1000).toString()) + expect(comp.find(DurationConsumer).props().duration.toString()).toEqual( + moment.duration(1000).toString() + ) }) it("updates duration every second", () => { @@ -31,6 +33,8 @@ describe("DurationProvider", () => { ) jest.advanceTimersByTime(1000) - expect(comp.find(DurationConsumer).props().duration.toString()).toEqual(moment.duration(0).toString()) + expect(comp.find(DurationConsumer).props().duration.toString()).toEqual( + moment.duration(0).toString() + ) }) }) diff --git a/src/lib/Components/Countdown/StateManager.tests.tsx b/src/lib/Components/Countdown/StateManager.tests.tsx index 2bda075171f..c9ef765efda 100644 --- a/src/lib/Components/Countdown/StateManager.tests.tsx +++ b/src/lib/Components/Countdown/StateManager.tests.tsx @@ -25,7 +25,9 @@ describe("StateManager", () => { /> ) - expect(comp.find(Countdown).props().duration.toString()).toEqual(moment.duration(1000).toString()) + expect(comp.find(Countdown).props().duration.toString()).toEqual( + moment.duration(1000).toString() + ) }) it("Transitions state when duration expires", () => { diff --git a/src/lib/Components/Countdown/StateManager.tsx b/src/lib/Components/Countdown/StateManager.tsx index 1679a2ee923..0b1faabde82 100644 --- a/src/lib/Components/Countdown/StateManager.tsx +++ b/src/lib/Components/Countdown/StateManager.tsx @@ -26,13 +26,19 @@ export class StateManager extends React.Component { // If this component receives a new tickerState as props, // update to use the new props. if (props.onCurrentTickerState().date !== state.previousTickerState.date) { - return { tickerState: props.onCurrentTickerState(), previousTickerState: props.onCurrentTickerState() } + return { + tickerState: props.onCurrentTickerState(), + previousTickerState: props.onCurrentTickerState(), + } } else { return null } } - state = { tickerState: this.props.onCurrentTickerState(), previousTickerState: this.props.onCurrentTickerState() } + state = { + tickerState: this.props.onCurrentTickerState(), + previousTickerState: this.props.onCurrentTickerState(), + } handleDurationEnd = () => { this.setState({ tickerState: this.props.onNextTickerState(this.state.tickerState) }) diff --git a/src/lib/Components/Countdown/Ticker.tsx b/src/lib/Components/Countdown/Ticker.tsx index e6f784b8270..0be77e5966e 100644 --- a/src/lib/Components/Countdown/Ticker.tsx +++ b/src/lib/Components/Countdown/Ticker.tsx @@ -45,7 +45,11 @@ interface LabeledTickerProps { textProps?: ExtractProps } -export const LabeledTicker: React.FC = ({ duration, renderSeparator, textProps }) => { +export const LabeledTicker: React.FC = ({ + duration, + renderSeparator, + textProps, +}) => { const sections = durationSections(duration, ["d", "h", "m", "s"]) return ( @@ -73,7 +77,9 @@ export const SimpleTicker: React.FC = ({ duration, separator, return ( {sections - .map(({ time, label }, idx) => (idx < sections.length - 1 ? time + label + separator : time + label)) + .map(({ time, label }, idx) => + idx < sections.length - 1 ? time + label + separator : time + label + ) .join("")} ) diff --git a/src/lib/Components/CountrySelect.tsx b/src/lib/Components/CountrySelect.tsx index cbacac01dbe..2719800ae71 100644 --- a/src/lib/Components/CountrySelect.tsx +++ b/src/lib/Components/CountrySelect.tsx @@ -5,25 +5,55 @@ import { Select, SelectOption } from "../../palette/elements/Select" // wikipedia article https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population export const COUNTRY_SELECT_OPTIONS: Array> = [ - { label: "Afghanistan", value: "AF", searchImportance: 32225560, searchTerms: ["Afghanistan", "AF"] }, - { label: "Åland Islands", value: "AX", searchImportance: 29981, searchTerms: ["Åland Islands", "AX"] }, + { + label: "Afghanistan", + value: "AF", + searchImportance: 32225560, + searchTerms: ["Afghanistan", "AF"], + }, + { + label: "Åland Islands", + value: "AX", + searchImportance: 29981, + searchTerms: ["Åland Islands", "AX"], + }, { label: "Albania", value: "AL", searchImportance: 2845955, searchTerms: ["Albania", "AL"] }, { label: "Algeria", value: "DZ", searchImportance: 43000000, searchTerms: ["Algeria", "DZ"] }, - { label: "American Samoa", value: "AS", searchImportance: 56700, searchTerms: ["American Samoa", "AS"] }, + { + label: "American Samoa", + value: "AS", + searchImportance: 56700, + searchTerms: ["American Samoa", "AS"], + }, { label: "Andorra", value: "AD", searchImportance: 77543, searchTerms: ["Andorra", "AD"] }, { label: "Angola", value: "AO", searchImportance: 31127674, searchTerms: ["Angola", "AO"] }, { label: "Anguilla", value: "AI", searchImportance: 14869, searchTerms: ["Anguilla", "AI"] }, { label: "Antarctica", value: "AQ", searchImportance: 1000, searchTerms: ["Antarctica", "AQ"] }, - { label: "Antigua and Barbuda", value: "AG", searchImportance: 96453, searchTerms: ["Antigua and Barbuda", "AG"] }, + { + label: "Antigua and Barbuda", + value: "AG", + searchImportance: 96453, + searchTerms: ["Antigua and Barbuda", "AG"], + }, { label: "Argentina", value: "AR", searchImportance: 45376763, searchTerms: ["Argentina", "AR"] }, { label: "Armenia", value: "AM", searchImportance: 2956900, searchTerms: ["Armenia", "AM"] }, { label: "Aruba", value: "AW", searchImportance: 112190, searchTerms: ["Aruba", "AW"] }, { label: "Australia", value: "AU", searchImportance: 25756880, searchTerms: ["Australia", "AU"] }, { label: "Austria", value: "AT", searchImportance: 8902600, searchTerms: ["Austria", "AT"] }, - { label: "Azerbaijan", value: "AZ", searchImportance: 10067108, searchTerms: ["Azerbaijan", "AZ"] }, + { + label: "Azerbaijan", + value: "AZ", + searchImportance: 10067108, + searchTerms: ["Azerbaijan", "AZ"], + }, { label: "Bahamas", value: "BS", searchImportance: 385340, searchTerms: ["Bahamas", "BS"] }, { label: "Bahrain", value: "BH", searchImportance: 1543300, searchTerms: ["Bahrain", "BH"] }, - { label: "Bangladesh", value: "BD", searchImportance: 168872634, searchTerms: ["Bangladesh", "BD"] }, + { + label: "Bangladesh", + value: "BD", + searchImportance: 168872634, + searchTerms: ["Bangladesh", "BD"], + }, { label: "Barbados", value: "BB", searchImportance: 287025, searchTerms: ["Barbados", "BB"] }, { label: "Belarus", value: "BY", searchImportance: 9397800, searchTerms: ["Belarus", "BY"] }, { label: "Belgium", value: "BE", searchImportance: 11528375, searchTerms: ["Belgium", "BE"] }, @@ -40,15 +70,30 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ }, { label: "Botswana", value: "BW", searchImportance: 2338851, searchTerms: ["Botswana", "BW"] }, { label: "Brazil", value: "BR", searchImportance: 211729470, searchTerms: ["Brazil", "BR"] }, - { label: "Brunei Darussalam", value: "BN", searchImportance: 459500, searchTerms: ["Brunei Darussalam", "BN"] }, + { + label: "Brunei Darussalam", + value: "BN", + searchImportance: 459500, + searchTerms: ["Brunei Darussalam", "BN"], + }, { label: "Bulgaria", value: "BG", searchImportance: 6951482, searchTerms: ["Bulgaria", "BG"] }, - { label: "Burkina Faso", value: "BF", searchImportance: 21510181, searchTerms: ["Burkina Faso", "BF"] }, + { + label: "Burkina Faso", + value: "BF", + searchImportance: 21510181, + searchTerms: ["Burkina Faso", "BF"], + }, { label: "Burundi", value: "BI", searchImportance: 10953317, searchTerms: ["Burundi", "BI"] }, { label: "Cambodia", value: "KH", searchImportance: 15288489, searchTerms: ["Cambodia", "KH"] }, { label: "Cameroon", value: "CM", searchImportance: 26545864, searchTerms: ["Cameroon", "CM"] }, { label: "Canada", value: "CA", searchImportance: 38083197, searchTerms: ["Canada", "CA"] }, { label: "Cape Verde", value: "CV", searchImportance: 550483, searchTerms: ["Cape Verde", "CV"] }, - { label: "Cayman Islands", value: "KY", searchImportance: 65813, searchTerms: ["Cayman Islands", "KY"] }, + { + label: "Cayman Islands", + value: "KY", + searchImportance: 65813, + searchTerms: ["Cayman Islands", "KY"], + }, { label: "Central African Republic", value: "CF", @@ -58,7 +103,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ { label: "Chad", value: "TD", searchImportance: 16244513, searchTerms: ["Chad", "TD"] }, { label: "Chile", value: "CL", searchImportance: 19458310, searchTerms: ["Chile", "CL"] }, { label: "China", value: "CN", searchImportance: 1403322440, searchTerms: ["China", "CN"] }, - { label: "Christmas Island", value: "CX", searchImportance: 1955, searchTerms: ["Christmas Island", "CX"] }, + { + label: "Christmas Island", + value: "CX", + searchImportance: 1955, + searchTerms: ["Christmas Island", "CX"], + }, { label: "Cocos (Keeling) Islands", value: "CC", @@ -74,21 +124,56 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 89561404, searchTerms: ["Congo, The Democratic Republic of the", "CD"], }, - { label: "Cook Islands", value: "CK", searchImportance: 15200, searchTerms: ["Cook Islands", "CK"] }, - { label: "Costa Rica", value: "CR", searchImportance: 5058007, searchTerms: ["Costa Rica", "CR"] }, - { label: "Cote D'Ivoire", value: "CI", searchImportance: 25823071, searchTerms: ["Cote D'Ivoire", "CI"] }, + { + label: "Cook Islands", + value: "CK", + searchImportance: 15200, + searchTerms: ["Cook Islands", "CK"], + }, + { + label: "Costa Rica", + value: "CR", + searchImportance: 5058007, + searchTerms: ["Costa Rica", "CR"], + }, + { + label: "Cote D'Ivoire", + value: "CI", + searchImportance: 25823071, + searchTerms: ["Cote D'Ivoire", "CI"], + }, { label: "Croatia", value: "HR", searchImportance: 4076246, searchTerms: ["Croatia", "HR"] }, { label: "Cuba", value: "CU", searchImportance: 11193470, searchTerms: ["Cuba", "CU"] }, { label: "Cyprus", value: "CY", searchImportance: 875900, searchTerms: ["Cyprus", "CY"] }, - { label: "Czech Republic", value: "CZ", searchImportance: 10693939, searchTerms: ["Czech Republic", "CZ"] }, + { + label: "Czech Republic", + value: "CZ", + searchImportance: 10693939, + searchTerms: ["Czech Republic", "CZ"], + }, { label: "Denmark", value: "DK", searchImportance: 5824857, searchTerms: ["Denmark", "DK"] }, { label: "Djibouti", value: "DJ", searchImportance: 1078373, searchTerms: ["Djibouti", "DJ"] }, { label: "Dominica", value: "DM", searchImportance: 71808, searchTerms: ["Dominica", "DM"] }, - { label: "Dominican Republic", value: "DO", searchImportance: 10448499, searchTerms: ["Dominican Republic", "DO"] }, + { + label: "Dominican Republic", + value: "DO", + searchImportance: 10448499, + searchTerms: ["Dominican Republic", "DO"], + }, { label: "Ecuador", value: "EC", searchImportance: 17516888, searchTerms: ["Ecuador", "EC"] }, { label: "Egypt", value: "EG", searchImportance: 100554998, searchTerms: ["Egypt", "EG"] }, - { label: "El Salvador", value: "SV", searchImportance: 6486201, searchTerms: ["El Salvador", "SV"] }, - { label: "Equatorial Guinea", value: "GQ", searchImportance: 1454789, searchTerms: ["Equatorial Guinea", "GQ"] }, + { + label: "El Salvador", + value: "SV", + searchImportance: 6486201, + searchTerms: ["El Salvador", "SV"], + }, + { + label: "Equatorial Guinea", + value: "GQ", + searchImportance: 1454789, + searchTerms: ["Equatorial Guinea", "GQ"], + }, { label: "Eritrea", value: "ER", searchImportance: 3497117, searchTerms: ["Eritrea", "ER"] }, { label: "Estonia", value: "EE", searchImportance: 1328976, searchTerms: ["Estonia", "EE"] }, { label: "Ethiopia", value: "ET", searchImportance: 98665000, searchTerms: ["Ethiopia", "ET"] }, @@ -98,12 +183,27 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 3198, searchTerms: ["Falkland Islands (Malvinas)", "FK"], }, - { label: "Faroe Islands", value: "FO", searchImportance: 52484, searchTerms: ["Faroe Islands", "FO"] }, + { + label: "Faroe Islands", + value: "FO", + searchImportance: 52484, + searchTerms: ["Faroe Islands", "FO"], + }, { label: "Fiji", value: "FJ", searchImportance: 884887, searchTerms: ["Fiji", "FJ"] }, { label: "Finland", value: "FI", searchImportance: 5498027, searchTerms: ["Finland", "FI"] }, { label: "France", value: "FR", searchImportance: 67067000, searchTerms: ["France", "FR"] }, - { label: "French Guiana", value: "GF", searchImportance: 290691, searchTerms: ["French Guiana", "GF"] }, - { label: "French Polynesia", value: "PF", searchImportance: 275918, searchTerms: ["French Polynesia", "PF"] }, + { + label: "French Guiana", + value: "GF", + searchImportance: 290691, + searchTerms: ["French Guiana", "GF"], + }, + { + label: "French Polynesia", + value: "PF", + searchImportance: 275918, + searchTerms: ["French Polynesia", "PF"], + }, { label: "French Southern and Antarctic Lands", value: "TF", @@ -124,7 +224,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ { label: "Guatemala", value: "GT", searchImportance: 16604026, searchTerms: ["Guatemala", "GT"] }, { label: "Guernsey", value: "GG", searchImportance: 63196, searchTerms: ["Guernsey", "GG"] }, { label: "Guinea", value: "GN", searchImportance: 12218357, searchTerms: ["Guinea", "GN"] }, - { label: "Guinea-Bissau", value: "GW", searchImportance: 1604528, searchTerms: ["Guinea-Bissau", "GW"] }, + { + label: "Guinea-Bissau", + value: "GW", + searchImportance: 1604528, + searchTerms: ["Guinea-Bissau", "GW"], + }, { label: "Guyana", value: "GY", searchImportance: 782766, searchTerms: ["Guyana", "GY"] }, { label: "Haiti", value: "HT", searchImportance: 11577779, searchTerms: ["Haiti", "HT"] }, { @@ -138,7 +243,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ { label: "Hungary", value: "HU", searchImportance: 9769000, searchTerms: ["Hungary", "HU"] }, { label: "Iceland", value: "IS", searchImportance: 366130, searchTerms: ["Iceland", "IS"] }, { label: "India", value: "IN", searchImportance: 1364120059, searchTerms: ["India", "IN"] }, - { label: "Indonesia", value: "ID", searchImportance: 269603400, searchTerms: ["Indonesia", "ID"] }, + { + label: "Indonesia", + value: "ID", + searchImportance: 269603400, + searchTerms: ["Indonesia", "ID"], + }, { label: "Iran, Islamic Republic Of", value: "IR", @@ -147,14 +257,24 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ }, { label: "Iraq", value: "IQ", searchImportance: 40150200, searchTerms: ["Iraq", "IQ"] }, { label: "Ireland", value: "IE", searchImportance: 4921500, searchTerms: ["Ireland", "IE"] }, - { label: "Isle of Man", value: "IM", searchImportance: 83314, searchTerms: ["Isle of Man", "IM"] }, + { + label: "Isle of Man", + value: "IM", + searchImportance: 83314, + searchTerms: ["Isle of Man", "IM"], + }, { label: "Israel", value: "IL", searchImportance: 9216070, searchTerms: ["Israel", "IL"] }, { label: "Italy", value: "IT", searchImportance: 60238522, searchTerms: ["Italy", "IT"] }, { label: "Jamaica", value: "JM", searchImportance: 2726667, searchTerms: ["Jamaica", "JM"] }, { label: "Japan", value: "JP", searchImportance: 125930000, searchTerms: ["Japan", "JP"] }, { label: "Jersey", value: "JE", searchImportance: 106800, searchTerms: ["Jersey", "JE"] }, { label: "Jordan", value: "JO", searchImportance: 10713832, searchTerms: ["Jordan", "JO"] }, - { label: "Kazakhstan", value: "KZ", searchImportance: 18729296, searchTerms: ["Kazakhstan", "KZ"] }, + { + label: "Kazakhstan", + value: "KZ", + searchImportance: 18729296, + searchTerms: ["Kazakhstan", "KZ"], + }, { label: "Kenya", value: "KE", searchImportance: 47564296, searchTerms: ["Kenya", "KE"] }, { label: "Kiribati", value: "KI", searchImportance: 120100, searchTerms: ["Kiribati", "KI"] }, { @@ -163,9 +283,19 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 25450000, searchTerms: ["Korea, Democratic People's Republic of", "KP"], }, - { label: "Korea, Republic of", value: "KR", searchImportance: 51780579, searchTerms: ["Korea, Republic of", "KR"] }, + { + label: "Korea, Republic of", + value: "KR", + searchImportance: 51780579, + searchTerms: ["Korea, Republic of", "KR"], + }, { label: "Kuwait", value: "KW", searchImportance: 4420110, searchTerms: ["Kuwait", "KW"] }, - { label: "Kyrgyzstan", value: "KG", searchImportance: 6533500, searchTerms: ["Kyrgyzstan", "KG"] }, + { + label: "Kyrgyzstan", + value: "KG", + searchImportance: 6533500, + searchTerms: ["Kyrgyzstan", "KG"], + }, { label: "Lao People's Democratic Republic", value: "LA", @@ -177,7 +307,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ { label: "Lesotho", value: "LS", searchImportance: 2007201, searchTerms: ["Lesotho", "LS"] }, { label: "Liberia", value: "LR", searchImportance: 4475353, searchTerms: ["Liberia", "LR"] }, { label: "Libya", value: "LY", searchImportance: 6871287, searchTerms: ["Libya", "LY"] }, - { label: "Liechtenstein", value: "LI", searchImportance: 38749, searchTerms: ["Liechtenstein", "LI"] }, + { + label: "Liechtenstein", + value: "LI", + searchImportance: 38749, + searchTerms: ["Liechtenstein", "LI"], + }, { label: "Lithuania", value: "LT", searchImportance: 2793353, searchTerms: ["Lithuania", "LT"] }, { label: "Luxembourg", value: "LU", searchImportance: 626108, searchTerms: ["Luxembourg", "LU"] }, { label: "Macau", value: "MO", searchImportance: 696100, searchTerms: ["Macau", "MO"] }, @@ -187,15 +322,35 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 2077132, searchTerms: ["North Macedonia, Republic of", "MK"], }, - { label: "Madagascar", value: "MG", searchImportance: 26251309, searchTerms: ["Madagascar", "MG"] }, + { + label: "Madagascar", + value: "MG", + searchImportance: 26251309, + searchTerms: ["Madagascar", "MG"], + }, { label: "Malawi", value: "MW", searchImportance: 19129952, searchTerms: ["Malawi", "MW"] }, { label: "Malaysia", value: "MY", searchImportance: 32826760, searchTerms: ["Malaysia", "MY"] }, { label: "Maldives", value: "MV", searchImportance: 374775, searchTerms: ["Maldives", "MV"] }, { label: "Mali", value: "ML", searchImportance: 20250833, searchTerms: ["Mali", "ML"] }, { label: "Malta", value: "MT", searchImportance: 493559, searchTerms: ["Malta", "MT"] }, - { label: "Marshall Islands", value: "MH", searchImportance: 55500, searchTerms: ["Marshall Islands", "MH"] }, - { label: "Martinique", value: "MQ", searchImportance: 30066648, searchTerms: ["Martinique", "MQ"] }, - { label: "Mauritania", value: "MR", searchImportance: 4077347, searchTerms: ["Mauritania", "MR"] }, + { + label: "Marshall Islands", + value: "MH", + searchImportance: 55500, + searchTerms: ["Marshall Islands", "MH"], + }, + { + label: "Martinique", + value: "MQ", + searchImportance: 30066648, + searchTerms: ["Martinique", "MQ"], + }, + { + label: "Mauritania", + value: "MR", + searchImportance: 4077347, + searchTerms: ["Mauritania", "MR"], + }, { label: "Mauritius", value: "MU", searchImportance: 1265475, searchTerms: ["Mauritius", "MU"] }, { label: "Mayotte", value: "YT", searchImportance: 270372, searchTerms: ["Mayotte", "YT"] }, { label: "Mexico", value: "MX", searchImportance: 127792286, searchTerms: ["Mexico", "MX"] }, @@ -216,20 +371,50 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ { label: "Montenegro", value: "ME", searchImportance: 622359, searchTerms: ["Montenegro", "ME"] }, { label: "Montserrat", value: "MS", searchImportance: 4989, searchTerms: ["Montserrat", "MS"] }, { label: "Morocco", value: "MA", searchImportance: 35942525, searchTerms: ["Morocco", "MA"] }, - { label: "Mozambique", value: "MZ", searchImportance: 30066648, searchTerms: ["Mozambique", "MZ"] }, + { + label: "Mozambique", + value: "MZ", + searchImportance: 30066648, + searchTerms: ["Mozambique", "MZ"], + }, { label: "Myanmar", value: "MM", searchImportance: 54817919, searchTerms: ["Myanmar", "MM"] }, { label: "Namibia", value: "NA", searchImportance: 2458936, searchTerms: ["Namibia", "NA"] }, { label: "Nauru", value: "NR", searchImportance: 11000, searchTerms: ["Nauru", "NR"] }, { label: "Nepal", value: "NP", searchImportance: 29996478, searchTerms: ["Nepal", "NP"] }, - { label: "Netherlands", value: "NL", searchImportance: 17482181, searchTerms: ["Netherlands", "NL"] }, - { label: "Netherlands Antilles", value: "AN", searchImportance: 227049, searchTerms: ["Netherlands Antilles", "AN"] }, - { label: "New Caledonia", value: "NC", searchImportance: 271407, searchTerms: ["New Caledonia", "NC"] }, - { label: "New Zealand", value: "NZ", searchImportance: 5008365, searchTerms: ["New Zealand", "NZ"] }, + { + label: "Netherlands", + value: "NL", + searchImportance: 17482181, + searchTerms: ["Netherlands", "NL"], + }, + { + label: "Netherlands Antilles", + value: "AN", + searchImportance: 227049, + searchTerms: ["Netherlands Antilles", "AN"], + }, + { + label: "New Caledonia", + value: "NC", + searchImportance: 271407, + searchTerms: ["New Caledonia", "NC"], + }, + { + label: "New Zealand", + value: "NZ", + searchImportance: 5008365, + searchTerms: ["New Zealand", "NZ"], + }, { label: "Nicaragua", value: "NI", searchImportance: 6460411, searchTerms: ["Nicaragua", "NI"] }, { label: "Niger", value: "NE", searchImportance: 22314743, searchTerms: ["Niger", "NE"] }, { label: "Nigeria", value: "NG", searchImportance: 206139587, searchTerms: ["Nigeria", "NG"] }, { label: "Niue", value: "NU", searchImportance: 1520, searchTerms: ["Niue", "NU"] }, - { label: "Norfolk Island", value: "NF", searchImportance: 2169, searchTerms: ["Norfolk Island", "NF"] }, + { + label: "Norfolk Island", + value: "NF", + searchImportance: 2169, + searchTerms: ["Norfolk Island", "NF"], + }, { label: "Northern Mariana Islands", value: "MP", @@ -247,27 +432,57 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchTerms: ["Palestinian Territory, Occupied", "PS"], }, { label: "Panama", value: "PA", searchImportance: 4218808, searchTerms: ["Panama", "PA"] }, - { label: "Papua New Guinea", value: "PG", searchImportance: 8935000, searchTerms: ["Papua New Guinea", "PG"] }, + { + label: "Papua New Guinea", + value: "PG", + searchImportance: 8935000, + searchTerms: ["Papua New Guinea", "PG"], + }, { label: "Paraguay", value: "PY", searchImportance: 7252672, searchTerms: ["Paraguay", "PY"] }, { label: "Peru", value: "PE", searchImportance: 32824358, searchTerms: ["Peru", "PE"] }, - { label: "Philippines", value: "PH", searchImportance: 108829500, searchTerms: ["Philippines", "PH"] }, + { + label: "Philippines", + value: "PH", + searchImportance: 108829500, + searchTerms: ["Philippines", "PH"], + }, { label: "Pitcairn", value: "PN", searchImportance: 50, searchTerms: ["Pitcairn", "PN"] }, { label: "Poland", value: "PL", searchImportance: 38379000, searchTerms: ["Poland", "PL"] }, { label: "Portugal", value: "PT", searchImportance: 10295909, searchTerms: ["Portugal", "PT"] }, - { label: "Puerto Rico", value: "PR", searchImportance: 3193694, searchTerms: ["Puerto Rico", "PR"] }, + { + label: "Puerto Rico", + value: "PR", + searchImportance: 3193694, + searchTerms: ["Puerto Rico", "PR"], + }, { label: "Qatar", value: "QA", searchImportance: 2795484, searchTerms: ["Qatar", "QA"] }, { label: "Réunion", value: "RE", searchImportance: 859959, searchTerms: ["Réunion", "RE"] }, { label: "Romania", value: "RO", searchImportance: 19405156, searchTerms: ["Romania", "RO"] }, - { label: "Russian Federation", value: "RU", searchImportance: 146748590, searchTerms: ["Russian Federation", "RU"] }, + { + label: "Russian Federation", + value: "RU", + searchImportance: 146748590, + searchTerms: ["Russian Federation", "RU"], + }, { label: "Rwanda", value: "RW", searchImportance: 12374397, searchTerms: ["Rwanda", "RW"] }, - { label: "Saint Helena", value: "SH", searchImportance: 6000, searchTerms: ["Saint Helena", "SH"] }, + { + label: "Saint Helena", + value: "SH", + searchImportance: 6000, + searchTerms: ["Saint Helena", "SH"], + }, { label: "Saint Kitts and Nevis", value: "KN", searchImportance: 52823, searchTerms: ["Saint Kitts and Nevis", "KN"], }, - { label: "Saint Lucia", value: "LC", searchImportance: 178696, searchTerms: ["Saint Lucia", "LC"] }, + { + label: "Saint Lucia", + value: "LC", + searchImportance: 178696, + searchTerms: ["Saint Lucia", "LC"], + }, { label: "Saint Pierre and Miquelon", value: "PM", @@ -288,17 +503,37 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 210240, searchTerms: ["São Tomé and Príncipe", "ST"], }, - { label: "Saudi Arabia", value: "SA", searchImportance: 34218169, searchTerms: ["Saudi Arabia", "SA"] }, + { + label: "Saudi Arabia", + value: "SA", + searchImportance: 34218169, + searchTerms: ["Saudi Arabia", "SA"], + }, { label: "Senegal", value: "SN", searchImportance: 16705608, searchTerms: ["Senegal", "SN"] }, { label: "Serbia", value: "RS", searchImportance: 6963764, searchTerms: ["Serbia", "RS"] }, { label: "Seychelles", value: "SC", searchImportance: 98055, searchTerms: ["Seychelles", "SC"] }, - { label: "Sierra Leone", value: "SL", searchImportance: 7901454, searchTerms: ["Sierra Leone", "SL"] }, + { + label: "Sierra Leone", + value: "SL", + searchImportance: 7901454, + searchTerms: ["Sierra Leone", "SL"], + }, { label: "Singapore", value: "SG", searchImportance: 5703600, searchTerms: ["Singapore", "SG"] }, { label: "Slovakia", value: "SK", searchImportance: 5457873, searchTerms: ["Slovakia", "SK"] }, { label: "Slovenia", value: "SI", searchImportance: 2095861, searchTerms: ["Slovenia", "SI"] }, - { label: "Solomon Islands", value: "SB", searchImportance: 680806, searchTerms: ["Solomon Islands", "SB"] }, + { + label: "Solomon Islands", + value: "SB", + searchImportance: 680806, + searchTerms: ["Solomon Islands", "SB"], + }, { label: "Somalia", value: "SO", searchImportance: 15893219, searchTerms: ["Somalia", "SO"] }, - { label: "South Africa", value: "ZA", searchImportance: 58775022, searchTerms: ["South Africa", "ZA"] }, + { + label: "South Africa", + value: "ZA", + searchImportance: 58775022, + searchTerms: ["South Africa", "ZA"], + }, { label: "South Georgia and the South Sandwich Islands", value: "GS", @@ -317,7 +552,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ }, { label: "Eswatini", value: "SZ", searchImportance: 1093238, searchTerms: ["Eswatini", "SZ"] }, { label: "Sweden", value: "SE", searchImportance: 10345449, searchTerms: ["Sweden", "SE"] }, - { label: "Switzerland", value: "CH", searchImportance: 8619259, searchTerms: ["Switzerland", "CH"] }, + { + label: "Switzerland", + value: "CH", + searchImportance: 8619259, + searchTerms: ["Switzerland", "CH"], + }, { label: "Syrian Arab Republic", value: "SY", @@ -330,7 +570,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 23596493, searchTerms: ["Taiwan, Province of China", "TW"], }, - { label: "Tajikistan", value: "TJ", searchImportance: 9127000, searchTerms: ["Tajikistan", "TJ"] }, + { + label: "Tajikistan", + value: "TJ", + searchImportance: 9127000, + searchTerms: ["Tajikistan", "TJ"], + }, { label: "Tanzania, United Republic of", value: "TZ", @@ -338,14 +583,29 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchTerms: ["Tanzania, United Republic of", "TZ"], }, { label: "Thailand", value: "TH", searchImportance: 66523092, searchTerms: ["Thailand", "TH"] }, - { label: "Timor-Leste", value: "TL", searchImportance: 1387149, searchTerms: ["Timor-Leste", "TL"] }, + { + label: "Timor-Leste", + value: "TL", + searchImportance: 1387149, + searchTerms: ["Timor-Leste", "TL"], + }, { label: "Togo", value: "TG", searchImportance: 7538000, searchTerms: ["Togo", "TG"] }, { label: "Tokelau", value: "TK", searchImportance: 1400, searchTerms: ["Tokelau", "TK"] }, { label: "Tonga", value: "TO", searchImportance: 100651, searchTerms: ["Tonga", "TO"] }, - { label: "Trinidad and Tobago", value: "TT", searchImportance: 1363985, searchTerms: ["Trinidad and Tobago", "TT"] }, + { + label: "Trinidad and Tobago", + value: "TT", + searchImportance: 1363985, + searchTerms: ["Trinidad and Tobago", "TT"], + }, { label: "Tunisia", value: "TN", searchImportance: 11722038, searchTerms: ["Tunisia", "TN"] }, { label: "Turkey", value: "TR", searchImportance: 83154997, searchTerms: ["Turkey", "TR"] }, - { label: "Turkmenistan", value: "TM", searchImportance: 6031187, searchTerms: ["Turkmenistan", "TM"] }, + { + label: "Turkmenistan", + value: "TM", + searchImportance: 6031187, + searchTerms: ["Turkmenistan", "TM"], + }, { label: "Turks and Caicos Islands", value: "TC", @@ -361,8 +621,18 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 9890400, searchTerms: ["United Arab Emirates", "AE", "UAE"], }, - { label: "United Kingdom", value: "GB", searchImportance: 66796807, searchTerms: ["United Kingdom", "GB", "UK"] }, - { label: "United States", value: "US", searchImportance: 329952186, searchTerms: ["United States", "US", "USA"] }, + { + label: "United Kingdom", + value: "GB", + searchImportance: 66796807, + searchTerms: ["United Kingdom", "GB", "UK"], + }, + { + label: "United States", + value: "US", + searchImportance: 329952186, + searchTerms: ["United States", "US", "USA"], + }, { label: "United States Minor Outlying Islands", value: "UM", @@ -370,7 +640,12 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchTerms: ["United States Minor Outlying Islands", "UM"], }, { label: "Uruguay", value: "UY", searchImportance: 3530912, searchTerms: ["Uruguay", "UY"] }, - { label: "Uzbekistan", value: "UZ", searchImportance: 34269199, searchTerms: ["Uzbekistan", "UZ"] }, + { + label: "Uzbekistan", + value: "UZ", + searchImportance: 34269199, + searchTerms: ["Uzbekistan", "UZ"], + }, { label: "Vanuatu", value: "VU", searchImportance: 304500, searchTerms: ["Vanuatu", "VU"] }, { label: "Venezuela", value: "VE", searchImportance: 32219521, searchTerms: ["Venezuela", "VE"] }, { label: "Viet Nam", value: "VN", searchImportance: 96208984, searchTerms: ["Viet Nam", "VN"] }, @@ -380,16 +655,40 @@ export const COUNTRY_SELECT_OPTIONS: Array> = [ searchImportance: 104578, searchTerms: ["Virgin Islands, British", "VG"], }, - { label: "Virgin Islands, U.S.", value: "VI", searchImportance: 104578, searchTerms: ["Virgin Islands, U.S.", "VI"] }, - { label: "Wallis and Futuna", value: "WF", searchImportance: 11700, searchTerms: ["Wallis and Futuna", "WF"] }, - { label: "Western Sahara", value: "EH", searchImportance: 582463, searchTerms: ["Western Sahara", "EH"] }, + { + label: "Virgin Islands, U.S.", + value: "VI", + searchImportance: 104578, + searchTerms: ["Virgin Islands, U.S.", "VI"], + }, + { + label: "Wallis and Futuna", + value: "WF", + searchImportance: 11700, + searchTerms: ["Wallis and Futuna", "WF"], + }, + { + label: "Western Sahara", + value: "EH", + searchImportance: 582463, + searchTerms: ["Western Sahara", "EH"], + }, { label: "Yemen", value: "YE", searchImportance: 29825968, searchTerms: ["Yemen", "YE"] }, { label: "Zambia", value: "ZM", searchImportance: 17885422, searchTerms: ["Zambia", "ZM"] }, { label: "Zimbabwe", value: "ZW", searchImportance: 15159624, searchTerms: ["Zimbabwe", "ZW"] }, ] export const CountrySelect: React.ComponentType< - Omit, "options" | "placeholder" | "title" | "enableSearch"> + Omit< + React.ComponentPropsWithRef, + "options" | "placeholder" | "title" | "enableSearch" + > > = (props) => ( - ) diff --git a/src/lib/Components/CustomShareSheet.tsx b/src/lib/Components/CustomShareSheet.tsx index cdfd10dd82b..d046810d252 100644 --- a/src/lib/Components/CustomShareSheet.tsx +++ b/src/lib/Components/CustomShareSheet.tsx @@ -9,11 +9,19 @@ interface CustomShareSheetProps { setVisible: (value: boolean) => void } -export const CustomShareSheet: React.FC = ({ children, visible, setVisible }) => { +export const CustomShareSheet: React.FC = ({ + children, + visible, + setVisible, +}) => { const { height: screenHeight } = useScreenDimensions() return ( - setVisible(false)}> + setVisible(false)} + > setVisible(false)}> Share @@ -28,7 +36,11 @@ interface CustomShareSheetItemProps { onPress?: () => void } -export const CustomShareSheetItem: React.FC = ({ title, Icon, onPress }) => ( +export const CustomShareSheetItem: React.FC = ({ + title, + Icon, + onPress, +}) => ( {Icon} diff --git a/src/lib/Components/Disappearable.tsx b/src/lib/Components/Disappearable.tsx index bb0fec0d1a7..6adbb3c56dd 100644 --- a/src/lib/Components/Disappearable.tsx +++ b/src/lib/Components/Disappearable.tsx @@ -6,50 +6,56 @@ import { useAnimatedValue } from "./StickyTabPage/reanimatedHelpers" export interface Disappearable { disappear(): Promise } -export const Disappearable = React.forwardRef>( - ({ children, animateScale = true }, ref) => { - const opacity = useAnimatedValue(1) - const scale = animateScale - ? useMemo(() => { - return Animated.interpolate(opacity, { - inputRange: [0, 1], - outputRange: [0.92, 1], - }) - }, []) - : 1 - const [showContent, setShowContent] = useState(true) +export const Disappearable = React.forwardRef< + Disappearable, + React.PropsWithChildren<{ animateScale?: boolean }> +>(({ children, animateScale = true }, ref) => { + const opacity = useAnimatedValue(1) + const scale = animateScale + ? useMemo(() => { + return Animated.interpolate(opacity, { + inputRange: [0, 1], + outputRange: [0.92, 1], + }) + }, []) + : 1 + const [showContent, setShowContent] = useState(true) - useImperativeHandle( - ref, - () => ({ - async disappear() { - // first the content fades away and shrinks a little - await new Promise((resolve) => { - if (__TEST__) { - // .start doesn't exist at test time - resolve() - return - } - Animated.spring(opacity, { - ...Animated.SpringUtils.makeDefaultConfig(), - stiffness: 800, - damping: 320, - restSpeedThreshold: 0.1, - toValue: 0, - }).start(() => resolve()) - }) - // then we configure an animation layout to happen before removing the content - await new Promise((resolve) => { - LayoutAnimation.configureNext(LayoutAnimation.create(210, "easeInEaseOut", "opacity"), resolve) - setShowContent(false) - }) - }, - }), - [] - ) + useImperativeHandle( + ref, + () => ({ + async disappear() { + // first the content fades away and shrinks a little + await new Promise((resolve) => { + if (__TEST__) { + // .start doesn't exist at test time + resolve() + return + } + Animated.spring(opacity, { + ...Animated.SpringUtils.makeDefaultConfig(), + stiffness: 800, + damping: 320, + restSpeedThreshold: 0.1, + toValue: 0, + }).start(() => resolve()) + }) + // then we configure an animation layout to happen before removing the content + await new Promise((resolve) => { + LayoutAnimation.configureNext( + LayoutAnimation.create(210, "easeInEaseOut", "opacity"), + resolve + ) + setShowContent(false) + }) + }, + }), + [] + ) - return showContent ? ( - {children} - ) : null - } -) + return showContent ? ( + + {children} + + ) : null +}) diff --git a/src/lib/Components/EntityList/index.tests.tsx b/src/lib/Components/EntityList/index.tests.tsx index 78b1f235fa8..76d2fcacb12 100644 --- a/src/lib/Components/EntityList/index.tests.tsx +++ b/src/lib/Components/EntityList/index.tests.tsx @@ -10,7 +10,14 @@ describe("EntityList", () => { @@ -32,7 +39,12 @@ describe("EntityList", () => { name: "Zarouhie Abdalian", href: "/artist/zarouhie-abdalian", }, - { internalID: "12345", slug: "derya-akay", name: "Derya Akay", href: "/artist/derya-akay" }, + { + internalID: "12345", + slug: "derya-akay", + name: "Derya Akay", + href: "/artist/derya-akay", + }, ]} count={20} displayedItems={2} diff --git a/src/lib/Components/EventTiming.tests.tsx b/src/lib/Components/EventTiming.tests.tsx index 5bcfeef4f93..adb9a562764 100644 --- a/src/lib/Components/EventTiming.tests.tsx +++ b/src/lib/Components/EventTiming.tests.tsx @@ -8,21 +8,33 @@ const currentTime = "2018-05-10T20:22:32.000Z" it("returns 'Closed' if the event is over", () => { const tree = renderWithWrappers( - + ) expect(extractText(tree.root)).toMatch("Closed") }) it("returns a count of days if the event is closing soon", () => { const tree = renderWithWrappers( - + ) expect(extractText(tree.root)).toMatch("Closes in 2 days") }) it("returns a countdown if the event ends within 24 hours", () => { const tree = renderWithWrappers( - + ) expect(extractText(tree.root)).toMatch("Closes in 03 : 01 : 59") }) diff --git a/src/lib/Components/EventTiming.tsx b/src/lib/Components/EventTiming.tsx index cfe8d6d622d..6b7d0d83a56 100644 --- a/src/lib/Components/EventTiming.tsx +++ b/src/lib/Components/EventTiming.tsx @@ -9,7 +9,11 @@ interface Props extends TextProps { } export const EventTiming: React.FC = ({ currentTime, startAt, endAt, ...rest }) => { - const { formattedTime } = useEventTiming({ currentTime, startAt: startAt ?? undefined, endAt: endAt ?? undefined }) + const { formattedTime } = useEventTiming({ + currentTime, + startAt: startAt ?? undefined, + endAt: endAt ?? undefined, + }) return ( diff --git a/src/lib/Components/FancyModal/FancyModal.tsx b/src/lib/Components/FancyModal/FancyModal.tsx index a4173f820a8..7950979d26c 100644 --- a/src/lib/Components/FancyModal/FancyModal.tsx +++ b/src/lib/Components/FancyModal/FancyModal.tsx @@ -2,8 +2,15 @@ import { useScreenDimensions } from "lib/utils/useScreenDimensions" import React, { useContext, useEffect, useRef, useState } from "react" import { Modal, Platform } from "react-native" import { useSafeAreaFrame } from "react-native-safe-area-context" -import { ArtsyKeyboardAvoidingView, ArtsyKeyboardAvoidingViewContext } from "../ArtsyKeyboardAvoidingView" -import { CARD_STACK_OVERLAY_HEIGHT, CARD_STACK_OVERLAY_Y_OFFSET, FancyModalAnimationPosition } from "./FancyModalCard" +import { + ArtsyKeyboardAvoidingView, + ArtsyKeyboardAvoidingViewContext, +} from "../ArtsyKeyboardAvoidingView" +import { + CARD_STACK_OVERLAY_HEIGHT, + CARD_STACK_OVERLAY_Y_OFFSET, + FancyModalAnimationPosition, +} from "./FancyModalCard" import { FancyModalContext } from "./FancyModalContext" export const FancyModal: React.FC<{ @@ -28,7 +35,8 @@ export const FancyModal: React.FC<{ } = useScreenDimensions() const frame = useSafeAreaFrame() - const actualMaxHeight = screenHeight - (top + CARD_STACK_OVERLAY_HEIGHT + CARD_STACK_OVERLAY_Y_OFFSET) + const actualMaxHeight = + screenHeight - (top + CARD_STACK_OVERLAY_HEIGHT + CARD_STACK_OVERLAY_Y_OFFSET) let height: number if (fullScreen) { @@ -70,7 +78,9 @@ export const FancyModal: React.FC<{ up to the maximum 'top' value, and then add padding if the keyboard comes up any more. I'd imagine it would have an API like */ - + {children} ) : null, @@ -102,7 +112,9 @@ export const FancyModal: React.FC<{ statusBarTranslucent onRequestClose={onBackgroundPressed} > - {card.jsx} + + {card.jsx} + ) } diff --git a/src/lib/Components/FancyModal/FancyModalCard.tsx b/src/lib/Components/FancyModal/FancyModalCard.tsx index f81a77a1b53..95c80d9e99a 100644 --- a/src/lib/Components/FancyModal/FancyModalCard.tsx +++ b/src/lib/Components/FancyModal/FancyModalCard.tsx @@ -49,7 +49,9 @@ export const FancyModalCard = React.forwardRef< const isRightAnimationPosition = animationPosition === "right" const backdropOpacity = useRef(new Animated.Value(0)).current const scale = useRef(new Animated.Value(1)).current - const translateY = useRef(new Animated.Value(isRootCard || isRightAnimationPosition ? 0 : props.height)).current + const translateY = useRef( + new Animated.Value(isRootCard || isRightAnimationPosition ? 0 : props.height) + ).current const translateX = useRef(new Animated.Value(isRightAnimationPosition ? screen.width : 0)).current const borderRadius = useRef(new Animated.Value(isRootCard || props.fullScreen ? 0 : 10)).current @@ -204,7 +206,11 @@ export const FancyModalCard = React.forwardRef< {/* We need to apply background color in this extra inner view otherwise there is some glitchy tearing sometimes when hiding the modal */} {props.children} diff --git a/src/lib/Components/FancyModal/FancyModalContext.tsx b/src/lib/Components/FancyModal/FancyModalContext.tsx index e8e3395f700..01b87553ce6 100644 --- a/src/lib/Components/FancyModal/FancyModalContext.tsx +++ b/src/lib/Components/FancyModal/FancyModalContext.tsx @@ -3,7 +3,13 @@ import { useScreenDimensions } from "lib/utils/useScreenDimensions" import { compact, flatten } from "lodash" import React, { RefObject, useEffect, useRef, useState } from "react" import { Animated, View } from "react-native" -import { AnimationCreator, ease, FancyModalAnimationPosition, FancyModalCard, spring } from "./FancyModalCard" +import { + AnimationCreator, + ease, + FancyModalAnimationPosition, + FancyModalCard, + spring, +} from "./FancyModalCard" /** * This is responsible for managing a stack of FancyModalCard instances, and making sure they are positioned correctly. @@ -33,7 +39,11 @@ class FancyModalCardStack { } getStackAnimations(createAnimation: AnimationCreator) { - return flatten(compact(this.stack.map((card) => card.current?.getStackAnimations(createAnimation, this.stack)))) + return flatten( + compact( + this.stack.map((card) => card.current?.getStackAnimations(createAnimation, this.stack)) + ) + ) } getRootCard(height: number, content: React.ReactNode) { diff --git a/src/lib/Components/FancyModal/FancyModalHeader.tsx b/src/lib/Components/FancyModal/FancyModalHeader.tsx index b15e816b4d4..e6e23af3e27 100644 --- a/src/lib/Components/FancyModal/FancyModalHeader.tsx +++ b/src/lib/Components/FancyModal/FancyModalHeader.tsx @@ -1,5 +1,14 @@ import { themeGet } from "@styled-system/theme-get" -import { ArrowLeftIcon, ArrowRightIcon, CloseIcon, Flex, Separator, ShareIcon, Text, useTheme } from "palette" +import { + ArrowLeftIcon, + ArrowRightIcon, + CloseIcon, + Flex, + Separator, + ShareIcon, + Text, + useTheme, +} from "palette" import React from "react" import { TouchableOpacity } from "react-native" import styled from "styled-components/native" diff --git a/src/lib/Components/Gene/About.tsx b/src/lib/Components/Gene/About.tsx index c741325c327..15eb3298e66 100644 --- a/src/lib/Components/Gene/About.tsx +++ b/src/lib/Components/Gene/About.tsx @@ -14,7 +14,9 @@ interface Props { const About: React.FC = ({ gene }) => { const relatedArtists = () => { - return (gene.trending_artists || []).length ? : null + return (gene.trending_artists || []).length ? ( + + ) : null } return ( diff --git a/src/lib/Components/Gene/GeneArtworks.tests.tsx b/src/lib/Components/Gene/GeneArtworks.tests.tsx index ee0bb45c456..2e8b80972bb 100644 --- a/src/lib/Components/Gene/GeneArtworks.tests.tsx +++ b/src/lib/Components/Gene/GeneArtworks.tests.tsx @@ -23,7 +23,8 @@ describe("GeneArtworks", () => { environment={environment} query={graphql` - query GeneArtworksTestsQuery($geneID: String!, $input: FilterArtworksInput) @relay_test_operation { + query GeneArtworksTestsQuery($geneID: String!, $input: FilterArtworksInput) + @relay_test_operation { gene(id: $geneID) { ...GeneArtworks_gene @arguments(input: $input) } diff --git a/src/lib/Components/Gene/GeneArtworks.tsx b/src/lib/Components/Gene/GeneArtworks.tsx index 2bd0f0b8e3b..17b54248710 100644 --- a/src/lib/Components/Gene/GeneArtworks.tsx +++ b/src/lib/Components/Gene/GeneArtworks.tsx @@ -41,7 +41,10 @@ export const GeneArtworks: React.FC = ({ gene, relay, openFil useEffect(() => { setJSX( - + ) }, [artworksTotal, openFilterModal]) @@ -71,7 +74,11 @@ export const GeneArtworks: React.FC = ({ gene, relay, openFil Showing {artworksTotal} works - + ) } @@ -179,7 +186,12 @@ export const GeneArtworksPaginationContainer = createPaginationContainer( } }, query: graphql` - query GeneArtworksPaginationQuery($id: ID!, $count: Int!, $cursor: String, $input: FilterArtworksInput) { + query GeneArtworksPaginationQuery( + $id: ID! + $count: Int! + $cursor: String + $input: FilterArtworksInput + ) { node(id: $id) { ... on Gene { ...GeneArtworks_gene @arguments(count: $count, cursor: $cursor, input: $input) diff --git a/src/lib/Components/Gene/Header.tsx b/src/lib/Components/Gene/Header.tsx index f98a57d65ad..fd04cb6c0c7 100644 --- a/src/lib/Components/Gene/Header.tsx +++ b/src/lib/Components/Gene/Header.tsx @@ -37,7 +37,9 @@ class Header extends React.Component { } @track((props) => ({ - action_name: props.gene.isFollowed ? Schema.ActionNames.GeneUnfollow : Schema.ActionNames.GeneFollow, + action_name: props.gene.isFollowed + ? Schema.ActionNames.GeneUnfollow + : Schema.ActionNames.GeneFollow, action_type: Schema.ActionTypes.Tap, owner_id: props.gene.internalID, owner_slug: props.gene.slug, @@ -97,7 +99,9 @@ class Header extends React.Component { } @track((props) => ({ - action_name: props.gene.isFollowed ? Schema.ActionNames.GeneFollow : Schema.ActionNames.GeneUnfollow, + action_name: props.gene.isFollowed + ? Schema.ActionNames.GeneFollow + : Schema.ActionNames.GeneUnfollow, action_type: Schema.ActionTypes.Success, owner_id: props.gene.internalID, owner_slug: props.gene.slug, @@ -111,7 +115,9 @@ class Header extends React.Component { } @track((props) => ({ - action_name: props.gene.isFollowed ? Schema.ActionNames.GeneFollow : Schema.ActionNames.GeneUnfollow, + action_name: props.gene.isFollowed + ? Schema.ActionNames.GeneFollow + : Schema.ActionNames.GeneUnfollow, action_type: Schema.ActionTypes.Fail, owner_id: props.gene.internalID, owner_slug: props.gene.slug, @@ -132,7 +138,11 @@ class Header extends React.Component { return ( - this.handleFollowChange()} /> + this.handleFollowChange()} + /> ) } diff --git a/src/lib/Components/GenericArtistSeriesRail.tsx b/src/lib/Components/GenericArtistSeriesRail.tsx index 9293db54723..dbdb8420675 100644 --- a/src/lib/Components/GenericArtistSeriesRail.tsx +++ b/src/lib/Components/GenericArtistSeriesRail.tsx @@ -20,7 +20,9 @@ import { useTracking } from "react-tracking" import styled from "styled-components/native" interface GenericArtistSeriesRailProps { - collections: CollectionArtistSeriesRail_collectionGroup["members"] | ArtistAbout_artist["iconicCollections"] + collections: + | CollectionArtistSeriesRail_collectionGroup["members"] + | ArtistAbout_artist["iconicCollections"] contextScreenOwnerType: Schema.OwnerEntityTypes.Collection | Schema.OwnerEntityTypes.Artist contextScreenOwnerId: string contextScreenOwnerSlug: string @@ -32,7 +34,8 @@ type GenericArtistSeriesItem = export const GenericArtistSeriesRail: React.FC = (props) => { const color = useColor() - const { collections, contextScreenOwnerType, contextScreenOwnerId, contextScreenOwnerSlug } = props + const { collections, contextScreenOwnerType, contextScreenOwnerId, contextScreenOwnerSlug } = + props const tracking = useTracking() @@ -58,7 +61,10 @@ export const GenericArtistSeriesRail: React.FC = ( ListFooterComponent={() => } ItemSeparatorComponent={() => } renderItem={({ item: result, index }) => { - const artworkImageURLs = extractNodes(result?.artworksConnection, (artwork) => artwork.image?.url!) + const artworkImageURLs = extractNodes( + result?.artworksConnection, + (artwork) => artwork.image?.url! + ) return ( = ( > - + = ( diff --git a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tests.tsx b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tests.tsx index 217400698ee..e45b68684e1 100644 --- a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tests.tsx +++ b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tests.tsx @@ -4,14 +4,25 @@ import { renderWithWrappers } from "lib/tests/renderWithWrappers" import { Text, TouchableHighlightColor } from "palette" import React from "react" import { act } from "react-test-renderer" -import { FilterProps, HeaderArtworksFilter, SeparatorWithSmoothOpacity } from "./HeaderArtworksFilter" +import { + FilterProps, + HeaderArtworksFilter, + SeparatorWithSmoothOpacity, +} from "./HeaderArtworksFilter" describe("HeaderArtworksFilter", () => { const onPress = jest.fn() const MockHeaderArtworksFilter = (props: Partial) => { const animationValue = useAnimatedValue(0) - return + return ( + + ) } it("renders without throwing an error", () => { diff --git a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tsx b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tsx index 6fd4b6df35e..3dd131ed44e 100644 --- a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tsx +++ b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilter.tsx @@ -76,9 +76,12 @@ export const HeaderArtworksFilter: React.FC = ({ total, animationVa return } // @ts-ignore - event.target.measure((x: number, y: number, width: number, height: number, pageX: number, pageY: number) => { - setPageY(pageY) - }) + event.target.measure( + // @ts-ignore + (x: number, y: number, width: number, height: number, pageX: number, pageY: number) => { + setPageY(pageY) + } + ) setOnLayoutCalled(true) } @@ -108,7 +111,8 @@ export const HeaderArtworksFilter: React.FC = ({ total, animationVa { translateY: animationValue?.interpolate({ - inputRange: filterPageY > 0 ? [0, filterPageY - ANIM_START, filterPageY] : [0, 0, 0], + inputRange: + filterPageY > 0 ? [0, filterPageY - ANIM_START, filterPageY] : [0, 0, 0], outputRange: filterPageY > 0 ? [0, 0, TRANSLATE_Y_VALUE] : [0, 0, 0], extrapolate: "clamp", }) ?? 0, @@ -124,7 +128,10 @@ export const HeaderArtworksFilter: React.FC = ({ total, animationVa { translateX: animationValue?.interpolate({ - inputRange: filterPageY > 0 ? [0, filterPageY - ANIM_START, filterPageY] : [0, 0, 0], + inputRange: + filterPageY > 0 + ? [0, filterPageY - ANIM_START, filterPageY] + : [0, 0, 0], outputRange: filterPageY > 0 ? [0, 0, TRANSLATE_X_VALUE] : [0, 0, 0], extrapolate: "clamp", }) ?? 0, diff --git a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tests.tsx b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tests.tsx index c0a8b27d31a..81966f40fce 100644 --- a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tests.tsx +++ b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tests.tsx @@ -1,4 +1,7 @@ -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { useAnimatedValue } from "lib/Scenes/Artwork/Components/ImageCarousel/useAnimatedValue" import { extractText } from "lib/tests/extractText" import { renderWithWrappers } from "lib/tests/renderWithWrappers" @@ -21,7 +24,11 @@ describe("HeaderArtworksFilterWithTotalArtworks", () => { }, } - const TestHeaderArtworksFilterWithTotalArtworks = ({ initialData }: { initialData?: ArtworkFiltersState }) => { + const TestHeaderArtworksFilterWithTotalArtworks = ({ + initialData, + }: { + initialData?: ArtworkFiltersState + }) => { const animationValue = useAnimatedValue(0) return ( @@ -31,7 +38,9 @@ describe("HeaderArtworksFilterWithTotalArtworks", () => { } const getWrapper = ({ initialData = initialState }: { initialData?: ArtworkFiltersState }) => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) return tree } diff --git a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tsx b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tsx index 29bd5010502..3052ed9a410 100644 --- a/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tsx +++ b/src/lib/Components/HeaderArtworksFilter/HeaderArtworksFilterWithTotalArtworks.tsx @@ -8,7 +8,9 @@ interface HeaderArtworksFilterWithTotalArtworksProps { onPress: () => void } -export const HeaderArtworksFilterWithTotalArtworks: React.FC = (props) => { +export const HeaderArtworksFilterWithTotalArtworks: React.FC< + HeaderArtworksFilterWithTotalArtworksProps +> = (props) => { const artworksTotal = ArtworksFiltersStore.useStoreState((state) => state.counts.total) ?? 0 return diff --git a/src/lib/Components/Home/ArtistRails/ArtistCard.tsx b/src/lib/Components/Home/ArtistRails/ArtistCard.tsx index cc3795c84f8..6111f6eb18d 100644 --- a/src/lib/Components/Home/ArtistRails/ArtistCard.tsx +++ b/src/lib/Components/Home/ArtistRails/ArtistCard.tsx @@ -56,7 +56,11 @@ export const ArtistCard: React.FC = ({ artist, onDismiss, onFol borderRadius={12} style={{ top: 6, right: 6, width: 24, height: 24 }} > - + @@ -66,7 +70,9 @@ export const ArtistCard: React.FC = ({ artist, onDismiss, onFol ) } -export const ArtistCardWrapper = styled.TouchableHighlight.attrs(() => ({ underlayColor: "transparent" }))` +export const ArtistCardWrapper = styled.TouchableHighlight.attrs(() => ({ + underlayColor: "transparent", +}))` width: ${ARTIST_CARD_WIDTH}px; overflow: hidden; ` diff --git a/src/lib/Components/Home/ArtistRails/ArtistRail.tsx b/src/lib/Components/Home/ArtistRails/ArtistRail.tsx index 8365c68a1d6..0b1fd186e1b 100644 --- a/src/lib/Components/Home/ArtistRails/ArtistRail.tsx +++ b/src/lib/Components/Home/ArtistRails/ArtistRail.tsx @@ -4,7 +4,13 @@ import React, { useImperativeHandle, useRef, useState } from "react" import { FlatList, View, ViewProps } from "react-native" -import { commitMutation, createFragmentContainer, fetchQuery, graphql, RelayProp } from "react-relay" +import { + commitMutation, + createFragmentContainer, + fetchQuery, + graphql, + RelayProp, +} from "react-relay" import HomeAnalytics from "lib/Scenes/Home/homeAnalytics" import { useTracking } from "react-tracking" @@ -28,7 +34,8 @@ import { CARD_WIDTH } from "../CardRailCard" import { CardRailFlatList, INTER_CARD_PADDING } from "../CardRailFlatList" import { ArtistCard } from "./ArtistCard" -interface SuggestedArtist extends Pick> { +interface SuggestedArtist + extends Pick> { _disappearable: Disappearable | null } @@ -64,7 +71,10 @@ const ArtistRail: React.FC = (props) => { const result = await fetchQuery( defaultEnvironment, graphql` - query ArtistRailNewSuggestionQuery($basedOnArtistId: String!, $excludeArtistIDs: [String!]!) { + query ArtistRailNewSuggestionQuery( + $basedOnArtistId: String! + $excludeArtistIDs: [String!]! + ) { artist(id: $basedOnArtistId) { related { suggestedConnection( @@ -84,13 +94,16 @@ const ArtistRail: React.FC = (props) => { } `, { - excludeArtistIDs: uniq(artists.map((a) => a.internalID).concat(dismissedArtistIds.current)), + excludeArtistIDs: uniq( + artists.map((a) => a.internalID).concat(dismissedArtistIds.current) + ), basedOnArtistId: basedOnArtist.internalID, } ).toPromise() const artist = - (result as ArtistRailNewSuggestionQueryResponse).artist?.related?.suggestedConnection?.edges?.[0]?.node ?? null + (result as ArtistRailNewSuggestionQueryResponse).artist?.related?.suggestedConnection + ?.edges?.[0]?.node ?? null return ( artist && { @@ -98,7 +111,9 @@ const ArtistRail: React.FC = (props) => { _disappearable: null, // make the basedOn for this suggestion fall back to either the artist this was actually based on (if followed) // or whatever _that_ artist suggestion was based on, if available. Transient basedOn! - basedOn: artist.basedOn ?? (basedOnArtist.isFollowed ? { name: basedOnArtist.name } : basedOnArtist.basedOn), + basedOn: + artist.basedOn ?? + (basedOnArtist.isFollowed ? { name: basedOnArtist.name } : basedOnArtist.basedOn), } ) } catch (e) { @@ -178,7 +193,10 @@ const ArtistRail: React.FC = (props) => { } const handleDismiss = async (artist: SuggestedArtist) => { - dismissedArtistIds.current = uniq([artist.internalID].concat(dismissedArtistIds.current)).slice(0, 100) + dismissedArtistIds.current = uniq([artist.internalID].concat(dismissedArtistIds.current)).slice( + 0, + 100 + ) await artist._disappearable?.disappear() setArtists((_artists) => _artists.filter((a) => a.internalID !== artist.internalID)) @@ -221,13 +239,22 @@ const ArtistRail: React.FC = (props) => { artist={artist as any} onPress={() => trackEvent( - HomeAnalytics.artistThumbnailTapEvent(props.rail.key, artist.internalID, artist.slug, index) + HomeAnalytics.artistThumbnailTapEvent( + props.rail.key, + artist.internalID, + artist.slug, + index + ) ) } onFollow={() => handleFollowChange(artist)} - onDismiss={props.rail.key === "SUGGESTED" ? undefined : () => handleDismiss(artist)} + onDismiss={ + props.rail.key === "SUGGESTED" ? undefined : () => handleDismiss(artist) + } /> - {index === artists.length - 1 ? null : } + {index === artists.length - 1 ? null : ( + + )} ) diff --git a/src/lib/Components/Home/ArtistRails/RecommendedArtistsRail.tsx b/src/lib/Components/Home/ArtistRails/RecommendedArtistsRail.tsx index be3135256c2..eb015f7878f 100644 --- a/src/lib/Components/Home/ArtistRails/RecommendedArtistsRail.tsx +++ b/src/lib/Components/Home/ArtistRails/RecommendedArtistsRail.tsx @@ -11,7 +11,12 @@ import { extractNodes } from "lib/utils/extractNodes" import { Flex, Spacer, Spinner } from "palette" import React, { useImperativeHandle, useRef, useState } from "react" import { FlatList, ViewProps } from "react-native" -import { commitMutation, createPaginationContainer, graphql, RelayPaginationProp } from "react-relay" +import { + commitMutation, + createPaginationContainer, + graphql, + RelayPaginationProp, +} from "react-relay" import { useTracking } from "react-tracking" import { CardRailFlatList } from "../CardRailFlatList" import { ArtistCard } from "./ArtistCard" @@ -68,7 +73,9 @@ export const RecommendedArtistsRail: React.FC { - trackEvent(tracks.tapFollowOrUnfollowArtist(!!artist.isFollowed, artist.internalID, artist.slug)) + trackEvent( + tracks.tapFollowOrUnfollowArtist(!!artist.isFollowed, artist.internalID, artist.slug) + ) followOrUnfollowArtist(artist) } diff --git a/src/lib/Components/Home/CardRailCard.tsx b/src/lib/Components/Home/CardRailCard.tsx index bbf9104066a..e706b1df114 100644 --- a/src/lib/Components/Home/CardRailCard.tsx +++ b/src/lib/Components/Home/CardRailCard.tsx @@ -3,7 +3,9 @@ import styled from "styled-components/native" export const CARD_WIDTH = 270 -export const CardRailCard = styled.TouchableHighlight.attrs(() => ({ underlayColor: "transparent" }))` +export const CardRailCard = styled.TouchableHighlight.attrs(() => ({ + underlayColor: "transparent", +}))` width: ${CARD_WIDTH}px; border: 1px solid ${themeGet("colors.black10")}; border-radius: 4px; diff --git a/src/lib/Components/Home/HeroUnit.tsx b/src/lib/Components/Home/HeroUnit.tsx index 66373292e78..c8672782404 100644 --- a/src/lib/Components/Home/HeroUnit.tsx +++ b/src/lib/Components/Home/HeroUnit.tsx @@ -8,7 +8,9 @@ import { View } from "react-native" import LinearGradient from "react-native-linear-gradient" import OpaqueImageView from "../OpaqueImageView/OpaqueImageView" -type UnitType = NonNullable[0]> +type UnitType = NonNullable< + NonNullable[0] +> interface Props { unit: UnitType @@ -33,7 +35,12 @@ export const HeroUnit: React.FC = ({ unit, onPress, isTrove = false }) => return ( - + { - + Opening hours diff --git a/src/lib/Components/Lists/AuctionResultListItem.tests.tsx b/src/lib/Components/Lists/AuctionResultListItem.tests.tsx index 15b93cd728f..635ab14e8ca 100644 --- a/src/lib/Components/Lists/AuctionResultListItem.tests.tsx +++ b/src/lib/Components/Lists/AuctionResultListItem.tests.tsx @@ -36,7 +36,12 @@ describe("AuctionResults", () => { render={({ props }) => { if (props?.artist) { const results = extractNodes(props.artist.auctionResultsConnection) - return null} /> + return ( + null} + /> + ) } return null }} @@ -171,6 +176,8 @@ describe("AuctionResults", () => { expect(tree.root.findByProps({ testID: "saleInfo" }).props.children).toContain("Jan 12, 2021") expect(tree.root.findAllByType(AuctionResultsMidEstimate)[0].props.value).toEqual("mid-1") - expect(tree.root.findAllByType(AuctionResultsMidEstimate)[0].props.shortDescription).toEqual("est") + expect(tree.root.findAllByType(AuctionResultsMidEstimate)[0].props.shortDescription).toEqual( + "est" + ) }) }) diff --git a/src/lib/Components/Lists/AuctionResultListItem.tsx b/src/lib/Components/Lists/AuctionResultListItem.tsx index a59035fc01b..ee63d483532 100644 --- a/src/lib/Components/Lists/AuctionResultListItem.tsx +++ b/src/lib/Components/Lists/AuctionResultListItem.tsx @@ -74,7 +74,9 @@ const AuctionResultListItem: React.FC = ({ )} {auctionResult.title} - {!!auctionResult.dateText && auctionResult.dateText !== "" && `, ${auctionResult.dateText}`} + {!!auctionResult.dateText && + auctionResult.dateText !== "" && + `, ${auctionResult.dateText}`} {!!auctionResult.mediumText && ( @@ -105,12 +107,21 @@ const AuctionResultListItem: React.FC = ({ )} {!!auctionResult.performance?.mid && ( - + )} ) : ( - + {auctionResultText(auctionResult)} @@ -123,40 +134,43 @@ const AuctionResultListItem: React.FC = ({ ) } -export const AuctionResultListItemFragmentContainer = createFragmentContainer(AuctionResultListItem, { - auctionResult: graphql` - fragment AuctionResultListItem_auctionResult on AuctionResult { - currency - dateText - id - internalID - artist { - name - } - images { - thumbnail { - url(version: "square140") - height - width - aspectRatio +export const AuctionResultListItemFragmentContainer = createFragmentContainer( + AuctionResultListItem, + { + auctionResult: graphql` + fragment AuctionResultListItem_auctionResult on AuctionResult { + currency + dateText + id + internalID + artist { + name } + images { + thumbnail { + url(version: "square140") + height + width + aspectRatio + } + } + estimate { + low + } + mediumText + organization + boughtIn + performance { + mid + } + priceRealized { + cents + display + displayUSD + } + saleDate + title } - estimate { - low - } - mediumText - organization - boughtIn - performance { - mid - } - priceRealized { - cents - display - displayUSD - } - saleDate - title - } - `, -}) + `, + } +) diff --git a/src/lib/Components/Lists/SavedItemRow.tsx b/src/lib/Components/Lists/SavedItemRow.tsx index 1d624a7c91e..d0310e4dc9c 100644 --- a/src/lib/Components/Lists/SavedItemRow.tsx +++ b/src/lib/Components/Lists/SavedItemRow.tsx @@ -14,7 +14,13 @@ interface SavedItemRowProps { size?: number } -export const SavedItemRow: React.FC = ({ href, name, image, square_image, size = 60 }) => { +export const SavedItemRow: React.FC = ({ + href, + name, + image, + square_image, + size = 60, +}) => { const color = useColor() const imageURL = image?.url return ( diff --git a/src/lib/Components/Lists/ShowItemRow.tsx b/src/lib/Components/Lists/ShowItemRow.tsx index 9b0d4234df5..5cab8447a34 100644 --- a/src/lib/Components/Lists/ShowItemRow.tsx +++ b/src/lib/Components/Lists/ShowItemRow.tsx @@ -139,17 +139,36 @@ export class ShowItemRow extends React.Component { )} {!!(show.partner && show.partner.name) && ( - + {show.partner.name} )} {!!show.name && ( - + {show.name} )} {!!(show.exhibition_period && show.status) && ( - + {show.status.includes("closed") ? show.status.charAt(0).toUpperCase() + show.status.slice(1) : exhibitionDates( diff --git a/src/lib/Components/LocationMap/LocationMap.tsx b/src/lib/Components/LocationMap/LocationMap.tsx index cc94ca9217d..19d00d9b334 100644 --- a/src/lib/Components/LocationMap/LocationMap.tsx +++ b/src/lib/Components/LocationMap/LocationMap.tsx @@ -87,7 +87,13 @@ export const tappedOnMap = ( return [ { title, - options: ["Open in Apple Maps", "Open in City Mapper", "Open in Google Maps", "Copy Address", "Cancel"], + options: [ + "Open in Apple Maps", + "Open in City Mapper", + "Open in Google Maps", + "Copy Address", + "Cancel", + ], get cancelButtonIndex() { return this.options.length - 1 }, @@ -216,7 +222,9 @@ export const LocationMap: React.FC = (props) => { return ( - showActionSheetWithOptions(...tappedOnMap(lat, lng, address, summary, partnerName, city, postalCode)) + showActionSheetWithOptions( + ...tappedOnMap(lat, lng, address, summary, partnerName, city, postalCode) + ) } > diff --git a/src/lib/Components/Markdown.tests.tsx b/src/lib/Components/Markdown.tests.tsx index 18933982191..287f24c986b 100644 --- a/src/lib/Components/Markdown.tests.tsx +++ b/src/lib/Components/Markdown.tests.tsx @@ -20,8 +20,12 @@ describe("Markdown", () => { ) expect(markdown.root.findAllByType(Text).length).toEqual(4) - expect(markdown.root.findAllByType(Text)[0].props.children[0]).toMatch("paragraph 1 has some text") - expect(markdown.root.findAllByType(Text)[2].props.children[0]).toMatch("paragraph 2 also has text") + expect(markdown.root.findAllByType(Text)[0].props.children[0]).toMatch( + "paragraph 1 has some text" + ) + expect(markdown.root.findAllByType(Text)[2].props.children[0]).toMatch( + "paragraph 2 also has text" + ) }) it("renders links as LinkText", () => { @@ -36,7 +40,9 @@ describe("Markdown", () => { ) expect(markdown.root.findAllByType(LinkText).length).toEqual(1) - expect(markdown.root.findAllByType(LinkText)[0].props.children[0]).toMatch("join the live auction") + expect(markdown.root.findAllByType(LinkText)[0].props.children[0]).toMatch( + "join the live auction" + ) markdown.root.findAllByType(LinkText)[0].props.onPress() @@ -74,7 +80,9 @@ describe("Markdown", () => { react: (node, output, state) => {output(node.content, state)}, }, } - const markdown = renderWithWrappers(Paragraph 1 has some text) + const markdown = renderWithWrappers( + Paragraph 1 has some text + ) expect(markdown.root.findAllByType(Text)[0].props.testID).toBe("foobar") }) diff --git a/src/lib/Components/MenuItem.tsx b/src/lib/Components/MenuItem.tsx index 50e185a0638..7e9801b2658 100644 --- a/src/lib/Components/MenuItem.tsx +++ b/src/lib/Components/MenuItem.tsx @@ -49,7 +49,13 @@ export const MenuItem: React.FC<{ {!!value && ( - + {value} diff --git a/src/lib/Components/Modals/LoadingModal.tsx b/src/lib/Components/Modals/LoadingModal.tsx index d946151f1d0..74a0417a60e 100644 --- a/src/lib/Components/Modals/LoadingModal.tsx +++ b/src/lib/Components/Modals/LoadingModal.tsx @@ -7,8 +7,19 @@ interface LoadingModalProps { } const LoadingModal: React.FC = ({ isVisible, ...rest }) => ( - - + + diff --git a/src/lib/Components/OpaqueImageView/OpaqueImageView.tsx b/src/lib/Components/OpaqueImageView/OpaqueImageView.tsx index e634eeb5a6f..e526010b40c 100644 --- a/src/lib/Components/OpaqueImageView/OpaqueImageView.tsx +++ b/src/lib/Components/OpaqueImageView/OpaqueImageView.tsx @@ -101,7 +101,9 @@ export default class OpaqueImageView extends React.Component { style.flex ) ) { - console.error("[OpaqueImageView] Either an aspect ratio or specific dimensions or flex should be specified.") + console.error( + "[OpaqueImageView] Either an aspect ratio or specific dimensions or flex should be specified." + ) } } } diff --git a/src/lib/Components/ParentAwareScrollView.tests.tsx b/src/lib/Components/ParentAwareScrollView.tests.tsx index f9de25416dd..f0bd0ac4ea5 100644 --- a/src/lib/Components/ParentAwareScrollView.tests.tsx +++ b/src/lib/Components/ParentAwareScrollView.tests.tsx @@ -21,7 +21,9 @@ describe("", () => { // react to the parent flatlist scroll by calling props.aFunc const AFlatList = () => ( props.aFunc(e)} />]} + data={[ + props.aFunc(e)} />, + ]} renderItem={({ item }) => item} /> ) diff --git a/src/lib/Components/ParentAwareScrollView.tsx b/src/lib/Components/ParentAwareScrollView.tsx index cee32541435..55f792ed348 100644 --- a/src/lib/Components/ParentAwareScrollView.tsx +++ b/src/lib/Components/ParentAwareScrollView.tsx @@ -70,7 +70,10 @@ class ParentAwareScrollView extends React.PureComponent isNestedInAVirtualizedListWithSameOrientation = (): boolean => { const virtualizedListContext = this.context?.virtualizedList - return !!(virtualizedListContext && virtualizedListContext.horizontal === (this.props.horizontal ?? false)) + return !!( + virtualizedListContext && + virtualizedListContext.horizontal === (this.props.horizontal ?? false) + ) } // The following methods are required by any parent VirtualizedList diff --git a/src/lib/Components/PartnerEntityHeader.tests.tsx b/src/lib/Components/PartnerEntityHeader.tests.tsx index 9c5e28ba654..d708031cd23 100644 --- a/src/lib/Components/PartnerEntityHeader.tests.tsx +++ b/src/lib/Components/PartnerEntityHeader.tests.tsx @@ -40,14 +40,19 @@ describe("PartnerEntityHeader", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } it("renders correctly", () => { const wrapper = getWrapper({ - Partner: () => ({ name: "Example Partner Name", cities: ["New York", "Berlin", "Tokyo", "Milan"] }), + Partner: () => ({ + name: "Example Partner Name", + cities: ["New York", "Berlin", "Tokyo", "Milan"], + }), }) const text = extractText(wrapper.root) diff --git a/src/lib/Components/PhoneInput/PhoneInput.tests.tsx b/src/lib/Components/PhoneInput/PhoneInput.tests.tsx index 75fa0a9b9ba..06c7994a86c 100644 --- a/src/lib/Components/PhoneInput/PhoneInput.tests.tsx +++ b/src/lib/Components/PhoneInput/PhoneInput.tests.tsx @@ -18,7 +18,12 @@ describe("PhoneInput", () => { it("renders an input with the phone number pre-filled", () => { const tree = renderWithWrappers( - + ) expect(tree.root.findAllByType(Input)).toHaveLength(1) expect(extractText(tree.root.findByType(Input))).toBe("🇬🇧+447825 577664") @@ -29,7 +34,12 @@ describe("PhoneInput", () => { }) it("renders an input with the phone number pre-filled", () => { const tree = renderWithWrappers( - + ) expect(tree.root.findAllByType(Input)).toHaveLength(1) expect(extractText(tree.root.findByType(Input))).toBe("🇬🇧+447825 577664") @@ -62,7 +72,12 @@ describe("PhoneInput", () => { it("calls onChange and onChangeText when the value changes", () => { const tree = renderWithWrappers( - + ) expect(onChange).not.toHaveBeenCalled() expect(onChangeText).not.toHaveBeenCalled() diff --git a/src/lib/Components/PhoneInput/PhoneInput.tsx b/src/lib/Components/PhoneInput/PhoneInput.tsx index ce4faf540fd..fe501e34a24 100644 --- a/src/lib/Components/PhoneInput/PhoneInput.tsx +++ b/src/lib/Components/PhoneInput/PhoneInput.tsx @@ -26,7 +26,11 @@ export const PhoneInput = React.forwardRef< const initialValues = cleanUserPhoneNumber(value ?? "") const [countryCode, setCountryCode] = useState(initialValues.countryCode) const [phoneNumber, setPhoneNumber] = useState( - formatPhoneNumber({ current: initialValues.phoneNumber, previous: initialValues.phoneNumber, countryCode }) + formatPhoneNumber({ + current: initialValues.phoneNumber, + previous: initialValues.phoneNumber, + countryCode, + }) ) const [validationMessage, setValidationMessage] = useState(undefined) const dialCode = countryIndex[countryCode].dialCode @@ -106,7 +110,9 @@ export const PhoneInput = React.forwardRef< placeholder={countryIndex[countryCode]?.mask?.replace(/9/g, "0")} placeholderTextColor={color("black30")} onChangeText={(newPhoneNumber) => - setPhoneNumber(formatPhoneNumber({ current: newPhoneNumber, previous: phoneNumber, countryCode })) + setPhoneNumber( + formatPhoneNumber({ current: newPhoneNumber, previous: phoneNumber, countryCode }) + ) } keyboardType="phone-pad" renderLeftHandSection={() => ( @@ -121,7 +127,11 @@ export const PhoneInput = React.forwardRef< onSelectValue={(newCountryCode) => { setCountryCode(newCountryCode) setPhoneNumber( - formatPhoneNumber({ current: phoneNumber, previous: phoneNumber, countryCode: newCountryCode }) + formatPhoneNumber({ + current: phoneNumber, + previous: phoneNumber, + countryCode: newCountryCode, + }) ) }} title="Country code" diff --git a/src/lib/Components/PhoneInput/cleanUserPhoneNumber.tests.ts b/src/lib/Components/PhoneInput/cleanUserPhoneNumber.tests.ts index bb07a1e4890..b366cfd8b39 100644 --- a/src/lib/Components/PhoneInput/cleanUserPhoneNumber.tests.ts +++ b/src/lib/Components/PhoneInput/cleanUserPhoneNumber.tests.ts @@ -3,32 +3,68 @@ import { cleanUserPhoneNumber } from "./cleanUserPhoneNumber" describe(cleanUserPhoneNumber, () => { it("handles +-prefixed numbers correctly", () => { - expect(cleanUserPhoneNumber("+33 32423 5342")).toEqual({ countryCode: "fr", phoneNumber: "324235342" }) - expect(cleanUserPhoneNumber("+18076221000")).toEqual({ countryCode: "ca", phoneNumber: "8076221000" }) - expect(cleanUserPhoneNumber("+1(555)-622-100")).toEqual({ countryCode: "us", phoneNumber: "555622100" }) + expect(cleanUserPhoneNumber("+33 32423 5342")).toEqual({ + countryCode: "fr", + phoneNumber: "324235342", + }) + expect(cleanUserPhoneNumber("+18076221000")).toEqual({ + countryCode: "ca", + phoneNumber: "8076221000", + }) + expect(cleanUserPhoneNumber("+1(555)-622-100")).toEqual({ + countryCode: "us", + phoneNumber: "555622100", + }) }) it("handles international dialing prefixes for different countries", () => { ;(getCountry as jest.Mock).mockReturnValueOnce("GB") - expect(cleanUserPhoneNumber("0044237482934")).toEqual({ countryCode: "gb", phoneNumber: "237482934" }) + expect(cleanUserPhoneNumber("0044237482934")).toEqual({ + countryCode: "gb", + phoneNumber: "237482934", + }) ;(getCountry as jest.Mock).mockReturnValueOnce("US") - expect(cleanUserPhoneNumber("0113343523453434")).toEqual({ countryCode: "fr", phoneNumber: "43523453434" }) + expect(cleanUserPhoneNumber("0113343523453434")).toEqual({ + countryCode: "fr", + phoneNumber: "43523453434", + }) ;(getCountry as jest.Mock).mockReturnValueOnce("US") - expect(cleanUserPhoneNumber("0111(555)-823-394")).toEqual({ countryCode: "us", phoneNumber: "555823394" }) + expect(cleanUserPhoneNumber("0111(555)-823-394")).toEqual({ + countryCode: "us", + phoneNumber: "555823394", + }) ;(getCountry as jest.Mock).mockReturnValueOnce("AU") - expect(cleanUserPhoneNumber("001149543645878")).toEqual({ countryCode: "de", phoneNumber: "543645878" }) + expect(cleanUserPhoneNumber("001149543645878")).toEqual({ + countryCode: "de", + phoneNumber: "543645878", + }) ;(getCountry as jest.Mock).mockReturnValueOnce("AU") - expect(cleanUserPhoneNumber("001449543645878")).toEqual({ countryCode: "de", phoneNumber: "543645878" }) + expect(cleanUserPhoneNumber("001449543645878")).toEqual({ + countryCode: "de", + phoneNumber: "543645878", + }) }) it("removes trunk codes when no country code is available", () => { ;(getCountry as jest.Mock).mockReturnValueOnce("GB") - expect(cleanUserPhoneNumber("07825577554")).toEqual({ countryCode: "gb", phoneNumber: "7825577554" }) + expect(cleanUserPhoneNumber("07825577554")).toEqual({ + countryCode: "gb", + phoneNumber: "7825577554", + }) ;(getCountry as jest.Mock).mockReturnValueOnce("US") - expect(cleanUserPhoneNumber("17187558131")).toEqual({ countryCode: "us", phoneNumber: "7187558131" }) + expect(cleanUserPhoneNumber("17187558131")).toEqual({ + countryCode: "us", + phoneNumber: "7187558131", + }) }) it("leaves the trunk code intact if it doesn't make sense in the user's current locale", () => { ;(getCountry as jest.Mock).mockReturnValueOnce("US") - expect(cleanUserPhoneNumber("07825577554")).toEqual({ countryCode: "us", phoneNumber: "07825577554" }) + expect(cleanUserPhoneNumber("07825577554")).toEqual({ + countryCode: "us", + phoneNumber: "07825577554", + }) ;(getCountry as jest.Mock).mockReturnValueOnce("GB") - expect(cleanUserPhoneNumber("17187558131")).toEqual({ countryCode: "gb", phoneNumber: "17187558131" }) + expect(cleanUserPhoneNumber("17187558131")).toEqual({ + countryCode: "gb", + phoneNumber: "17187558131", + }) }) }) diff --git a/src/lib/Components/Photos/AddEditPhotos.tsx b/src/lib/Components/Photos/AddEditPhotos.tsx index 5a20f157f3d..2146512c88b 100644 --- a/src/lib/Components/Photos/AddEditPhotos.tsx +++ b/src/lib/Components/Photos/AddEditPhotos.tsx @@ -7,7 +7,17 @@ import { isPad } from "lib/utils/hardware" import { showPhotoActionSheet } from "lib/utils/requestPhotos" import { useScreenDimensions } from "lib/utils/useScreenDimensions" import { chunk } from "lodash" -import { AddIcon, BorderBox, Box, Button, Flex, Separator, Spacer, useColor, XCircleIcon } from "palette" +import { + AddIcon, + BorderBox, + Box, + Button, + Flex, + Separator, + Spacer, + useColor, + XCircleIcon, +} from "palette" import React, { useState } from "react" import { Image, ScrollView, TouchableOpacity } from "react-native" import { Image as RNCImage } from "react-native-image-crop-picker" @@ -20,7 +30,11 @@ interface AddEditPhotosProps { navigator: NavigatorIOS } -export const AddEditPhotos: React.FC = ({ initialPhotos, photosUpdated, navigator }) => { +export const AddEditPhotos: React.FC = ({ + initialPhotos, + photosUpdated, + navigator, +}) => { const [photos, setPhotos] = useState(initialPhotos) const { width: screenWidth } = useScreenDimensions() @@ -43,7 +57,9 @@ export const AddEditPhotos: React.FC = ({ initialPhotos, pho navigator.pop() } - const items = [].concat( + const items = [ + , + ].concat( photos.map((photo, index) => { return ( @@ -82,10 +98,10 @@ export const AddEditPhotos: React.FC = ({ initialPhotos, pho ) } -const AddPhotosButton: React.FC<{ imageSize: number; addPhotos: (addedImages: RNCImage[]) => void }> = ({ - imageSize, - addPhotos, -}) => { +const AddPhotosButton: React.FC<{ + imageSize: number + addPhotos: (addedImages: RNCImage[]) => void +}> = ({ imageSize, addPhotos }) => { const color = useColor() const { showActionSheetWithOptions } = useActionSheet() @@ -98,7 +114,13 @@ const AddPhotosButton: React.FC<{ imageSize: number; addPhotos: (addedImages: RN }) }} > - + diff --git a/src/lib/Components/Photos/AddEditPhotos_tests.tsx b/src/lib/Components/Photos/AddEditPhotos_tests.tsx index 493858b89a3..89d945e4c12 100644 --- a/src/lib/Components/Photos/AddEditPhotos_tests.tsx +++ b/src/lib/Components/Photos/AddEditPhotos_tests.tsx @@ -70,7 +70,11 @@ describe("AddEditPhotos", () => { const initialPhotos = [fakePhoto("path1"), fakePhoto("path2"), fakePhoto("path3")] const tree = renderWithWrappers( - + ) const images = tree.root.findAllByType(Image) expect(images.length).toEqual(3) diff --git a/src/lib/Components/PopIn.tsx b/src/lib/Components/PopIn.tsx index 9a0270c1d5c..13bdc7c87fb 100644 --- a/src/lib/Components/PopIn.tsx +++ b/src/lib/Components/PopIn.tsx @@ -1,10 +1,19 @@ import React, { useEffect, useRef } from "react" import { Animated } from "react-native" -export const PopIn: React.FC<{ xOffset?: number; yOffset?: number }> = ({ children, xOffset, yOffset }) => { +export const PopIn: React.FC<{ xOffset?: number; yOffset?: number }> = ({ + children, + xOffset, + yOffset, +}) => { const entranceProgress = useRef(new Animated.Value(0)).current useEffect(() => { - Animated.spring(entranceProgress, { toValue: 1, bounciness: 12, speed: 28, useNativeDriver: true }).start() + Animated.spring(entranceProgress, { + toValue: 1, + bounciness: 12, + speed: 28, + useNativeDriver: true, + }).start() }, []) return ( - action("item tapped")} /> + action("item tapped")} + /> +export type PopoverMessageItem = Omit< + PopoverMessageProps, + "translateYAnimation" | "opacityAnimation" +> export interface PopoverMessageProps { placement?: PopoverMessagePlacement @@ -59,7 +62,16 @@ export const getColorsByType = (type?: PopoverMessageType) => { // TODO: Remove NAVBAR_HEIGHT when a new design without a floating back button is added export const PopoverMessage: React.FC = (props) => { const color = useColor() - const { placement = "top", title, message, type, translateYAnimation, opacityAnimation, onPress, onUndoPress } = props + const { + placement = "top", + title, + message, + type, + translateYAnimation, + opacityAnimation, + onPress, + onUndoPress, + } = props const { safeAreaInsets } = useScreenDimensions() const { hide } = usePopoverMessage() const colors = getColorsByType(type) @@ -95,7 +107,11 @@ export const PopoverMessage: React.FC = (props) => { {!!onUndoPress && ( - + Undo @@ -110,8 +126,14 @@ export const PopoverMessage: React.FC = (props) => { position="absolute" left="1" right="1" - bottom={placement === "bottom" ? safeAreaInsets.bottom + EDGE_POPOVER_MESSAGE_PADDING : undefined} - top={placement === "top" ? safeAreaInsets.top + EDGE_POPOVER_MESSAGE_PADDING + NAVBAR_HEIGHT : undefined} + bottom={ + placement === "bottom" ? safeAreaInsets.bottom + EDGE_POPOVER_MESSAGE_PADDING : undefined + } + top={ + placement === "top" + ? safeAreaInsets.top + EDGE_POPOVER_MESSAGE_PADDING + NAVBAR_HEIGHT + : undefined + } style={{ opacity, transform: [{ translateY }], diff --git a/src/lib/Components/PopoverMessage/PopoverMessageProvider.tsx b/src/lib/Components/PopoverMessage/PopoverMessageProvider.tsx index b057e8070a3..7022ee6ede2 100644 --- a/src/lib/Components/PopoverMessage/PopoverMessageProvider.tsx +++ b/src/lib/Components/PopoverMessage/PopoverMessageProvider.tsx @@ -105,7 +105,11 @@ export const PopoverMessageProvider: React.FC = ({ children }) => { {children} {!!popoverMessage && ( - + )} ) diff --git a/src/lib/Components/PrefetchFlatList.tsx b/src/lib/Components/PrefetchFlatList.tsx index 12dbdfa853a..d442c141d69 100644 --- a/src/lib/Components/PrefetchFlatList.tsx +++ b/src/lib/Components/PrefetchFlatList.tsx @@ -24,10 +24,13 @@ export function PrefetchFlatList({ }: PrefetchFlatListProps) { const prefetchUrl = usePrefetch() - const [viewedUrls, addViewedUrl] = useReducer((state: { [key: string]: boolean }, url: string) => { - state[url] = true - return state - }, {}) + const [viewedUrls, addViewedUrl] = useReducer( + (state: { [key: string]: boolean }, url: string) => { + state[url] = true + return state + }, + {} + ) const viewabilityConfigRef = useRef({ waitForInteraction: true, diff --git a/src/lib/Components/ReadMore.tests.tsx b/src/lib/Components/ReadMore.tests.tsx index 422b0ed2f4f..51d5ce0f261 100644 --- a/src/lib/Components/ReadMore.tests.tsx +++ b/src/lib/Components/ReadMore.tests.tsx @@ -46,7 +46,11 @@ describe("ReadMore", () => { it("Shows the 'Read more' link when the length of the text is > the number of characters allowed", () => { const { queryByText, getAllByText, UNSAFE_queryAllByType } = renderWithWrappersTL( - + ) expect(extractText(UNSAFE_queryAllByType(RNText)[0])).toBe(`This te... Read${nbsp}more`) diff --git a/src/lib/Components/ReadMore.tsx b/src/lib/Components/ReadMore.tsx index 96c2d963d5d..a7aeff78f1c 100644 --- a/src/lib/Components/ReadMore.tsx +++ b/src/lib/Components/ReadMore.tsx @@ -2,7 +2,16 @@ import { plainTextFromTree } from "lib/utils/plainTextFromTree" import { defaultRules, renderMarkdown } from "lib/utils/renderMarkdown" import { Schema } from "lib/utils/track" import _ from "lodash" -import { Color, emdash, Flex, nbsp, Sans, SansProps, Text as PaletteText, TextProps as PaletteTextProps } from "palette" +import { + Color, + emdash, + Flex, + nbsp, + Sans, + SansProps, + Text as PaletteText, + TextProps as PaletteTextProps, +} from "palette" import React, { useState } from "react" import { Text } from "react-native" import { useTracking } from "react-tracking" @@ -40,7 +49,8 @@ export const ReadMore = React.memo( const TextComponent: React.ComponentType = ( textStyle === "new" ? PaletteText : Sans ) as any - const textProps: SansProps | PaletteTextProps = textStyle === "new" ? { variant: "xs" } : { size: "3" } + const textProps: SansProps | PaletteTextProps = + textStyle === "new" ? { variant: "xs" } : { size: "3" } const rules = { ...basicRules, ...(type === "show" && { diff --git a/src/lib/Components/RelatedArtists/RelatedArtist.tsx b/src/lib/Components/RelatedArtists/RelatedArtist.tsx index ee2d723e1e6..4458c2ac3af 100644 --- a/src/lib/Components/RelatedArtists/RelatedArtist.tsx +++ b/src/lib/Components/RelatedArtists/RelatedArtist.tsx @@ -26,7 +26,10 @@ class RelatedArtist extends Component { return ( - + {artist.name} @@ -45,7 +48,10 @@ class RelatedArtist extends Component { artworksString(counts: RelatedArtist_artist["counts"]) { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const totalWorks = counts.artworks ? counts.artworks + (counts.artworks > 1 ? " works" : " work") : null + const totalWorks = counts.artworks + ? // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + counts.artworks + (counts.artworks > 1 ? " works" : " work") + : null // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 if (totalWorks && counts.forSaleArtworks === counts.artworks) { return totalWorks + " for sale" diff --git a/src/lib/Components/RetryErrorBoundary.tests.tsx b/src/lib/Components/RetryErrorBoundary.tests.tsx index edcd94bfbb8..5f34e99f1c2 100644 --- a/src/lib/Components/RetryErrorBoundary.tests.tsx +++ b/src/lib/Components/RetryErrorBoundary.tests.tsx @@ -14,7 +14,9 @@ afterEach(() => { }) it("Renders the fallback view when the rendered component crashes", () => { - const tree = renderWithWrappers( } />) + const tree = renderWithWrappers( + } /> + ) expect(tree.root.findAllByType(LoadFailureView)).toHaveLength(1) }) diff --git a/src/lib/Components/RetryErrorBoundary.tsx b/src/lib/Components/RetryErrorBoundary.tsx index ada5cd7b60d..a15598e404d 100644 --- a/src/lib/Components/RetryErrorBoundary.tsx +++ b/src/lib/Components/RetryErrorBoundary.tsx @@ -34,7 +34,9 @@ export class RetryErrorBoundaryLegacy extends React.Component { const { render } = this.props const containers = { [ErrorState.Okay]: () => render({ isRetry: false }), - [ErrorState.Error]: () => this.setState({ errorState: ErrorState.Retry })} />, + [ErrorState.Error]: () => ( + this.setState({ errorState: ErrorState.Retry })} /> + ), [ErrorState.Retry]: () => render({ isRetry: true }), } return containers[this.state.errorState]() @@ -49,7 +51,10 @@ interface RetryErrorBoundaryState { error: Error | null } -export class RetryErrorBoundary extends React.Component { +export class RetryErrorBoundary extends React.Component< + RetryErrorBoundaryProps, + RetryErrorBoundaryState +> { static getDerivedStateFromError(error: Error | null): RetryErrorBoundaryState { return { error } } diff --git a/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tests.tsx b/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tests.tsx index b474dd6546d..dbf4f94c995 100644 --- a/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tests.tsx +++ b/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tests.tsx @@ -17,7 +17,10 @@ interface TestRendererProps { describe("SaleArtworkTileRailCard", () => { let mockEnvironment: ReturnType - const TestRenderer = ({ useCustomSaleMessage = false, useSquareAspectRatio = false }: TestRendererProps) => ( + const TestRenderer = ({ + useCustomSaleMessage = false, + useSquareAspectRatio = false, + }: TestRendererProps) => ( environment={mockEnvironment} query={graphql` diff --git a/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tsx b/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tsx index 7f7ef2469ae..a3825b69fb3 100644 --- a/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tsx +++ b/src/lib/Components/SaleArtworkTileRailCard/SaleArtworkTileRailCard.tsx @@ -1,4 +1,10 @@ -import { ContextModule, OwnerType, ScreenOwnerType, tappedEntityGroup, TappedEntityGroupArgs } from "@artsy/cohesion" +import { + ContextModule, + OwnerType, + ScreenOwnerType, + tappedEntityGroup, + TappedEntityGroupArgs, +} from "@artsy/cohesion" import { themeGet } from "@styled-system/theme-get" import { SaleArtworkTileRailCard_saleArtwork } from "__generated__/SaleArtworkTileRailCard_saleArtwork.graphql" import { Box, Flex, Text, useColor } from "palette" @@ -55,7 +61,9 @@ export const SaleArtworkTileRailCard: React.FC = ( throw new Error("imageAspectRatio is required for non-square images") } - const imageWidth = useSquareAspectRatio ? CONTAINER_HEIGHT : (artwork.image?.aspectRatio ?? 1) * CONTAINER_HEIGHT + const imageWidth = useSquareAspectRatio + ? CONTAINER_HEIGHT + : (artwork.image?.aspectRatio ?? 1) * CONTAINER_HEIGHT const imageDisplay = artwork.image?.imageURL ? ( = ( }} /> ) : ( - + ) const artistNamesDisplay = artwork.artistNames ? ( diff --git a/src/lib/Components/ScrollableTabBar.tsx b/src/lib/Components/ScrollableTabBar.tsx index ac22d3db366..f7beb9ce690 100644 --- a/src/lib/Components/ScrollableTabBar.tsx +++ b/src/lib/Components/ScrollableTabBar.tsx @@ -57,7 +57,10 @@ export const ScrollableTab: React.FC = ({ children }) => ( export interface ScrollableTabBarState { activeTab: number } -export default class ScrollableTabBar extends React.Component { +export default class ScrollableTabBar extends React.Component< + ScrollableTabBarProps, + ScrollableTabBarState +> { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 scrollView: ScrollView = null // Default to screen width under first render diff --git a/src/lib/Components/SearchInput.tests.tsx b/src/lib/Components/SearchInput.tests.tsx index 8d1e02a77ee..3e3b7e359d5 100644 --- a/src/lib/Components/SearchInput.tests.tsx +++ b/src/lib/Components/SearchInput.tests.tsx @@ -14,7 +14,14 @@ describe("SearchInput", () => { const TestWrapper = (props: SearchInputProps) => { const ref = { current: null as null | TextInput } - return + return ( + + ) } beforeEach(() => { @@ -71,9 +78,8 @@ describe("SearchInput", () => { }) it(`hides "x" button when pressing "Cancel"`, () => { - const { getAllByText, getByA11yLabel, queryAllByA11yLabel, getByPlaceholderText } = renderWithWrappersTL( - - ) + const { getAllByText, getByA11yLabel, queryAllByA11yLabel, getByPlaceholderText } = + renderWithWrappersTL() const searchInput = getByPlaceholderText("Type something...") fireEvent(searchInput, "changeText", "text") expect(getByA11yLabel("Clear input button")).toBeTruthy() @@ -82,9 +88,8 @@ describe("SearchInput", () => { }) it('should hide "Cancel" when it is pressed', () => { - const { queryAllByA11yLabel, getAllByText, findAllByA11yLabel, getByPlaceholderText } = renderWithWrappersTL( - - ) + const { queryAllByA11yLabel, getAllByText, findAllByA11yLabel, getByPlaceholderText } = + renderWithWrappersTL() fireEvent.changeText(getByPlaceholderText("Type something..."), "text") expect(findAllByA11yLabel("Cancel")).toBeTruthy() diff --git a/src/lib/Components/SearchInput.tsx b/src/lib/Components/SearchInput.tsx index 571cce6b1ee..fc1b38daa1a 100644 --- a/src/lib/Components/SearchInput.tsx +++ b/src/lib/Components/SearchInput.tsx @@ -1,5 +1,14 @@ import SearchIcon from "lib/Icons/SearchIcon" -import { emitInputClearEvent, Flex, Input, InputProps, Sans, SpacingUnitV2, SpacingUnitV3, useSpace } from "palette" +import { + emitInputClearEvent, + Flex, + Input, + InputProps, + Sans, + SpacingUnitV2, + SpacingUnitV3, + useSpace, +} from "palette" import React, { useImperativeHandle, useRef } from "react" import { TextInput, TouchableOpacity, useWindowDimensions } from "react-native" import Animated, { Easing } from "react-native-reanimated" diff --git a/src/lib/Components/SectionTitle.tests.tsx b/src/lib/Components/SectionTitle.tests.tsx index f2bb7afad46..c7c10ccbc0b 100644 --- a/src/lib/Components/SectionTitle.tests.tsx +++ b/src/lib/Components/SectionTitle.tests.tsx @@ -23,7 +23,9 @@ describe("SectionTitle", () => { it(`renders a right arrow when given an 'onPress' prop`, async () => { const onPress = jest.fn() - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(extractText(tree.root.findByProps({ testID: "title" }))).toContain("Hello") expect(extractText(tree.root.findByProps({ testID: "subtitle" }))).toBe("welcome to test") diff --git a/src/lib/Components/ShareSheet/ShareSheet.tests.tsx b/src/lib/Components/ShareSheet/ShareSheet.tests.tsx index a38e62506d7..5c611b3a6ef 100644 --- a/src/lib/Components/ShareSheet/ShareSheet.tests.tsx +++ b/src/lib/Components/ShareSheet/ShareSheet.tests.tsx @@ -102,7 +102,10 @@ describe("ShareSheet", () => { it("should hide item if showInstagram props is set to false", async () => { const { queryByText } = renderWithWrappersTL( - + ) expect(queryByText("Instagram Stories")).toBeFalsy() diff --git a/src/lib/Components/ShareSheet/ShareSheet.tsx b/src/lib/Components/ShareSheet/ShareSheet.tsx index 9052dee9adb..511b2346991 100644 --- a/src/lib/Components/ShareSheet/ShareSheet.tsx +++ b/src/lib/Components/ShareSheet/ShareSheet.tsx @@ -142,7 +142,11 @@ export const ShareSheet: React.FC = (props) => { ) : null} {showWhatsapp && canOpenWhatsapp ? ( - } onPress={handleShareOnWhatsAppPress} /> + } + onPress={handleShareOnWhatsAppPress} + /> ) : null} {entry.imageURL && showInstagram && canOpenInstagram ? ( @@ -161,7 +165,12 @@ export const ShareSheet: React.FC = (props) => { } export const tracks = { - share: (contextModule: ContextModule, ownerType: OwnerType, entry: ShareEntry, service: string): Share => ({ + share: ( + contextModule: ContextModule, + ownerType: OwnerType, + entry: ShareEntry, + service: string + ): Share => ({ action: ActionType.share, context_module: contextModule, context_owner_type: ownerType, diff --git a/src/lib/Components/Show/ShowArtistsPreview.tests.tsx b/src/lib/Components/Show/ShowArtistsPreview.tests.tsx index bf14fac797f..5e2b9aab782 100644 --- a/src/lib/Components/Show/ShowArtistsPreview.tests.tsx +++ b/src/lib/Components/Show/ShowArtistsPreview.tests.tsx @@ -89,7 +89,9 @@ describe("ArtistsContainer", () => { await flushPromiseQueue() - expect(env.mock.getMostRecentOperation().request.node.operation.name).toEqual("ArtistListItemFollowArtistMutation") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toEqual( + "ArtistListItemFollowArtistMutation" + ) expect(env.mock.getMostRecentOperation().request.variables).toMatchInlineSnapshot(` Object { "input": Object { diff --git a/src/lib/Components/Show/ShowArtistsPreview.tsx b/src/lib/Components/Show/ShowArtistsPreview.tsx index 87572694b69..86a39a4b0ab 100644 --- a/src/lib/Components/Show/ShowArtistsPreview.tsx +++ b/src/lib/Components/Show/ShowArtistsPreview.tsx @@ -37,7 +37,10 @@ export class ShowArtistsPreview extends React.Component { const { show, onViewAllArtistsPressed, Component } = this.props const artistsShown = 5 // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const artists = get(show, (s) => s.artists, []).concat(get(show, (s) => s.artists_without_artworks, [])) + const artists = get(show, (s) => s.artists, []).concat( + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + get(show, (s) => s.artists_without_artworks, []) + ) const items = compact(take(artists, artistsShown)) return ( @@ -56,7 +59,10 @@ export class ShowArtistsPreview extends React.Component { {artists.length > artistsShown && ( <> - onViewAllArtistsPressed()} /> + onViewAllArtistsPressed()} + /> )} diff --git a/src/lib/Components/Stack.tsx b/src/lib/Components/Stack.tsx index 8fec9f03ca1..08a298d2cc7 100644 --- a/src/lib/Components/Stack.tsx +++ b/src/lib/Components/Stack.tsx @@ -6,7 +6,9 @@ export const Stack: React.FC< > = ({ children, spacing = 2, horizontal, ...others }) => { return ( - }>{children} + }> + {children} + ) } diff --git a/src/lib/Components/StickyHeaderPage.tsx b/src/lib/Components/StickyHeaderPage.tsx index 20d6adbad59..a02cd2e100c 100644 --- a/src/lib/Components/StickyHeaderPage.tsx +++ b/src/lib/Components/StickyHeaderPage.tsx @@ -15,8 +15,10 @@ interface StickyHeaderPageProps { export const StickyHeaderPage: React.FC = (props) => { const { headerContent, stickyHeaderContent, footerContent, children } = props - const { jsx: staticHeader, nativeHeight: headerHeight } = useAutoCollapsingMeasuredView(headerContent) - const { jsx: stickyHeader, nativeHeight: stickyHeaderHeight } = useAutoCollapsingMeasuredView(stickyHeaderContent) + const { jsx: staticHeader, nativeHeight: headerHeight } = + useAutoCollapsingMeasuredView(headerContent) + const { jsx: stickyHeader, nativeHeight: stickyHeaderHeight } = + useAutoCollapsingMeasuredView(stickyHeaderContent) const footerOffsetY = useAnimatedValue(-1) const scrollOffsetY = useAnimatedValue(0) const { width: screenWidth } = useScreenDimensions() @@ -24,7 +26,11 @@ export const StickyHeaderPage: React.FC = (props) => { const shouldHideBackButton = Animated.greaterOrEq(scrollOffsetY, 10) - const headerHeightRendered = Animated.cond(Animated.neq(headerHeight, new Animated.Value(-1)), headerHeight, 0) + const headerHeightRendered = Animated.cond( + Animated.neq(headerHeight, new Animated.Value(-1)), + headerHeight, + 0 + ) const stickyHeaderOffsetY = Animated.max(Animated.sub(headerHeightRendered, scrollOffsetY), 0) const stickyHeaderHeightRendered = Animated.cond( @@ -83,7 +89,9 @@ export const StickyHeaderPage: React.FC = (props) => { {children} {!!footerContent && ( - + {footerContent} )} diff --git a/src/lib/Components/StickyTabPage/StickyTabPage.tsx b/src/lib/Components/StickyTabPage/StickyTabPage.tsx index c47a90bf904..ac2995dca2f 100644 --- a/src/lib/Components/StickyTabPage/StickyTabPage.tsx +++ b/src/lib/Components/StickyTabPage/StickyTabPage.tsx @@ -58,8 +58,11 @@ export const StickyTabPage: React.FC = ({ ) const activeTabIndexNative = useAnimatedValue(initialTabIndex) const [activeTabIndex, setActiveTabIndex] = useGlobalState(initialTabIndex) - const [tabSpecificStickyHeaderContent, setTabSpecificStickyHeaderContent] = useState>([]) - const { jsx: staticHeader, nativeHeight: staticHeaderHeight } = useAutoCollapsingMeasuredView(staticHeaderContent) + const [tabSpecificStickyHeaderContent, setTabSpecificStickyHeaderContent] = useState< + Array + >([]) + const { jsx: staticHeader, nativeHeight: staticHeaderHeight } = + useAutoCollapsingMeasuredView(staticHeaderContent) const stickyRailRef = useRef(null) @@ -71,7 +74,8 @@ export const StickyTabPage: React.FC = ({ return useAutoCollapsingMeasuredView(tabSpecificStickyHeaderContent[i]) }) - const { jsx: stickyHeader, nativeHeight: stickyHeaderHeight } = useAutoCollapsingMeasuredView(stickyHeaderContent) + const { jsx: stickyHeader, nativeHeight: stickyHeaderHeight } = + useAutoCollapsingMeasuredView(stickyHeaderContent) const tracking = useTracking() const headerOffsetY = useAnimatedValue(0) const railRef = useRef(null) @@ -119,14 +123,19 @@ export const StickyTabPage: React.FC = ({ {!!Animated.neq(stickyHeaderHeight, new Animated.Value(-1)) && !!Animated.neq(staticHeaderHeight, new Animated.Value(-1)) && ( - + {tabs.map(({ content }, index) => { return ( setTabSpecificStickyHeaderContent((prev) => { const newArray = prev.slice(0) diff --git a/src/lib/Components/StickyTabPage/StickyTabPageFlatList.tsx b/src/lib/Components/StickyTabPage/StickyTabPageFlatList.tsx index c29136a9aa8..e34b5ebc250 100644 --- a/src/lib/Components/StickyTabPage/StickyTabPageFlatList.tsx +++ b/src/lib/Components/StickyTabPage/StickyTabPageFlatList.tsx @@ -29,7 +29,10 @@ export interface StickyTabSection { content: JSX.Element } export interface StickyTabFlatListProps - extends Omit, "onScroll" | "data" | "scrollEventThrottle" | "ListHeaderComponent" | "renderItem"> { + extends Omit< + FlatListProps, + "onScroll" | "data" | "scrollEventThrottle" | "ListHeaderComponent" | "renderItem" + > { data: StickyTabSection[] paddingHorizontal?: number innerRef?: React.MutableRefObject<{ getNode(): FlatList } | null> @@ -194,7 +197,10 @@ function useStickyHeaderPositioning({ // y offset got smaller so scrolling up (content travels down the screen) // if velocity is high enough or we're already moving the header up or we're near the top of the scroll view // then move the header down (show it) - Animated.set(amountScrolledUpward, Animated.add(amountScrolledUpward, Animated.abs(scrollDiff))), + Animated.set( + amountScrolledUpward, + Animated.add(amountScrolledUpward, Animated.abs(scrollDiff)) + ), Animated.cond(Animated.or(upwardScrollThresholdBreached, headerIsNotFullyUp, nearTheTop), [ Animated.set(headerOffsetY, Animated.min(0, Animated.sub(headerOffsetY, scrollDiff))), ]), @@ -204,7 +210,10 @@ function useStickyHeaderPositioning({ // we don't want to manipulate the header position while bouncing at the top or the bottom of the scroll view // cause it feels weeeird const notBouncingAtTheTop = Animated.greaterThan(scrollOffsetY, 0) - const notBouncingAtTheBottom = Animated.lessThan(scrollOffsetY, Animated.sub(contentHeight, layoutHeight)) + const notBouncingAtTheBottom = Animated.lessThan( + scrollOffsetY, + Animated.sub(contentHeight, layoutHeight) + ) const updateHeaderOffsetWhenNotBouncing = Animated.cond( Animated.and(notBouncingAtTheTop, notBouncingAtTheBottom), @@ -225,13 +234,19 @@ function useStickyHeaderPositioning({ // y offset got bigger so scrolling down (content travels up the screen) Animated.set( headerOffsetY, - Animated.max(negative(staticHeaderHeight), Animated.sub(headerOffsetY, scrollDiff)) + Animated.max( + negative(staticHeaderHeight), + Animated.sub(headerOffsetY, scrollDiff) + ) ), ], [ // y offset got smaller so scrolling up (content travels down the screen) Animated.cond(Animated.or(headerIsNotFullyUp, nearTheTop), [ - Animated.set(headerOffsetY, Animated.min(0, Animated.sub(headerOffsetY, scrollDiff))), + Animated.set( + headerOffsetY, + Animated.min(0, Animated.sub(headerOffsetY, scrollDiff)) + ), ]), ] ), diff --git a/src/lib/Components/StickyTabPage/StickyTabPageScrollView.tsx b/src/lib/Components/StickyTabPage/StickyTabPageScrollView.tsx index 31a2444d122..557b246480a 100644 --- a/src/lib/Components/StickyTabPage/StickyTabPageScrollView.tsx +++ b/src/lib/Components/StickyTabPage/StickyTabPageScrollView.tsx @@ -1,6 +1,9 @@ import React from "react" import { StickyTabFlatListProps, StickyTabPageFlatList } from "./StickyTabPageFlatList" -export const StickyTabPageScrollView: React.FC> = ({ children, ...others }) => { +export const StickyTabPageScrollView: React.FC> = ({ + children, + ...others +}) => { return {children} }]} {...others} /> } diff --git a/src/lib/Components/StickyTabPage/StickyTabPageTabBar.tsx b/src/lib/Components/StickyTabPage/StickyTabPageTabBar.tsx index bf09f6f7472..982800ea242 100644 --- a/src/lib/Components/StickyTabPage/StickyTabPageTabBar.tsx +++ b/src/lib/Components/StickyTabPage/StickyTabPageTabBar.tsx @@ -2,16 +2,24 @@ import { useScreenDimensions } from "lib/utils/useScreenDimensions" import { Sans } from "palette" import { NavigationalTabs } from "palette/elements/Tabs" import React, { useEffect, useRef, useState } from "react" -import { Animated, LayoutRectangle, ScrollView, TouchableOpacity, View, ViewProps } from "react-native" +import { + Animated, + LayoutRectangle, + ScrollView, + TouchableOpacity, + View, + ViewProps, +} from "react-native" import { useStickyTabPageContext } from "./SitckyTabPageContext" export const TAB_BAR_HEIGHT = 48 -export const StickyTabPageTabBar: React.FC<{ onTabPress?(tab: { label: string; index: number }): void }> = ({ - onTabPress, -}) => { +export const StickyTabPageTabBar: React.FC<{ + onTabPress?(tab: { label: string; index: number }): void +}> = ({ onTabPress }) => { const screen = useScreenDimensions() - const { tabLabels, activeTabIndex, setActiveTabIndex, tabSuperscripts } = useStickyTabPageContext() + const { tabLabels, activeTabIndex, setActiveTabIndex, tabSuperscripts } = + useStickyTabPageContext() activeTabIndex.useUpdates() const [tabLayouts] = useState>(tabLabels.map(() => null)) diff --git a/src/lib/Components/StyledWebView.tsx b/src/lib/Components/StyledWebView.tsx index 39c78f48983..40e22978d1b 100644 --- a/src/lib/Components/StyledWebView.tsx +++ b/src/lib/Components/StyledWebView.tsx @@ -14,7 +14,10 @@ export const StyledWebView: React.FC<{ body: string }> = ({ body }) => { }, [webViewHeight]) // @ts-ignore - const htmlOutput = SimpleMarkdown.htmlFor(SimpleMarkdown.ruleOutput(SimpleMarkdown.defaultRules, "html")) + const htmlOutput = SimpleMarkdown.htmlFor( + // @ts-ignore + SimpleMarkdown.ruleOutput(SimpleMarkdown.defaultRules, "html") + ) const html = ` diff --git a/src/lib/Components/SwitchMenu.tsx b/src/lib/Components/SwitchMenu.tsx index dc1168dbddf..0c00183be76 100644 --- a/src/lib/Components/SwitchMenu.tsx +++ b/src/lib/Components/SwitchMenu.tsx @@ -10,7 +10,13 @@ interface SwitchMenuProps { disabled?: boolean } -export const SwitchMenu = ({ onChange, value, title, description, disabled = false }: SwitchMenuProps) => { +export const SwitchMenu = ({ + onChange, + value, + title, + description, + disabled = false, +}: SwitchMenuProps) => { const color = useColor() return ( @@ -24,7 +30,10 @@ export const SwitchMenu = ({ onChange, value, title, description, disabled = fal = ({ children }) => {children} +export const Tab: React.FC = ({ children }) => ( + {children} +) export default class TabBar extends React.Component { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 diff --git a/src/lib/Components/Tag/TagArtworks.tests.tsx b/src/lib/Components/Tag/TagArtworks.tests.tsx index 3a282c2d327..ad4655344dc 100644 --- a/src/lib/Components/Tag/TagArtworks.tests.tsx +++ b/src/lib/Components/Tag/TagArtworks.tests.tsx @@ -23,7 +23,8 @@ describe("TagArtworks", () => { environment={environment} query={graphql` - query TagArtworksTestsQuery($tagID: String!, $input: FilterArtworksInput) @relay_test_operation { + query TagArtworksTestsQuery($tagID: String!, $input: FilterArtworksInput) + @relay_test_operation { tag(id: $tagID) { ...TagArtworks_tag @arguments(input: $input) } diff --git a/src/lib/Components/Tag/TagArtworks.tsx b/src/lib/Components/Tag/TagArtworks.tsx index ad80b8606f2..83b8941ce29 100644 --- a/src/lib/Components/Tag/TagArtworks.tsx +++ b/src/lib/Components/Tag/TagArtworks.tsx @@ -47,7 +47,10 @@ export const TagArtworks: React.FC = ({ tag, relay, openFilter - + ) }, [artworksTotal, openFilterModal]) @@ -185,7 +188,12 @@ export const TagArtworksPaginationContainer = createPaginationContainer( } }, query: graphql` - query TagArtworksPaginationQuery($id: String!, $count: Int!, $cursor: String, $input: FilterArtworksInput) { + query TagArtworksPaginationQuery( + $id: String! + $count: Int! + $cursor: String + $input: FilterArtworksInput + ) { tag(id: $id) { ...TagArtworks_tag @arguments(count: $count, cursor: $cursor, input: $input) } diff --git a/src/lib/Components/Toast/ToastComponent.tsx b/src/lib/Components/Toast/ToastComponent.tsx index 4fcea20c772..3343cbecd65 100644 --- a/src/lib/Components/Toast/ToastComponent.tsx +++ b/src/lib/Components/Toast/ToastComponent.tsx @@ -16,7 +16,14 @@ const NAVBAR_HEIGHT = 44 type ToastProps = ToastDetails -export const ToastComponent: React.FC = ({ id, positionIndex, placement, message, onPress, Icon }) => { +export const ToastComponent: React.FC = ({ + id, + positionIndex, + placement, + message, + onPress, + Icon, +}) => { const color = useColor() const { width, height } = useScreenDimensions() const { top: topSafeAreaInset } = useScreenDimensions().safeAreaInsets diff --git a/src/lib/Components/Toast/toastHook.tsx b/src/lib/Components/Toast/toastHook.tsx index 2b7cec3093a..ffc90535346 100644 --- a/src/lib/Components/Toast/toastHook.tsx +++ b/src/lib/Components/Toast/toastHook.tsx @@ -6,8 +6,14 @@ import { ToastDetails, ToastPlacement } from "./types" type ToastContextValue = typeof Toast -// tslint:disable-next-line:no-empty -const ToastContext = React.createContext({ show: () => {}, hide: () => {}, hideOldest: () => {} }) +const ToastContext = React.createContext({ + // tslint:disable-next-line:no-empty + show: () => {}, + // tslint:disable-next-line:no-empty + hide: () => {}, + // tslint:disable-next-line:no-empty + hideOldest: () => {}, +}) const useToastContext = () => useContext(ToastContext) export const useToast = () => { diff --git a/src/lib/Components/WithCurrentTime.tsx b/src/lib/Components/WithCurrentTime.tsx index 53cfec9ec3f..0e8d98f60a5 100644 --- a/src/lib/Components/WithCurrentTime.tsx +++ b/src/lib/Components/WithCurrentTime.tsx @@ -31,7 +31,11 @@ interface WithCurrentTimeProps { children: (currentTime: string) => React.ReactElement } -export const WithCurrentTime: React.FC = ({ children, interval = 1000, syncWithServer }) => { +export const WithCurrentTime: React.FC = ({ + children, + interval = 1000, + syncWithServer, +}) => { const [currentTime, setCurrentTime] = useState(getCurrentTimeAsIsoString()) const [timeOffsetInMilliseconds, setTimeOffsetInMilliseconds] = useState(0) let intervalId: NodeJS.Timeout @@ -54,5 +58,7 @@ export const WithCurrentTime: React.FC = ({ children, inte } }, []) - return children(DateTime.fromISO(currentTime).minus({ millisecond: timeOffsetInMilliseconds }).toString()) + return children( + DateTime.fromISO(currentTime).minus({ millisecond: timeOffsetInMilliseconds }).toString() + ) } diff --git a/src/lib/Components/WorksForYou/Notification.tsx b/src/lib/Components/WorksForYou/Notification.tsx index 94851d4f7b0..08edbc801b8 100644 --- a/src/lib/Components/WorksForYou/Notification.tsx +++ b/src/lib/Components/WorksForYou/Notification.tsx @@ -1,5 +1,12 @@ import React from "react" -import { Image, ImageStyle, StyleSheet, TouchableWithoutFeedback, View, ViewStyle } from "react-native" +import { + Image, + ImageStyle, + StyleSheet, + TouchableWithoutFeedback, + View, + ViewStyle, +} from "react-native" import { createFragmentContainer, graphql } from "react-relay" import GenericGrid from "../ArtworkGrids/GenericGrid" @@ -20,7 +27,8 @@ const HORIZONTAL_PADDING = 20 export class Notification extends React.Component { handleArtistTap() { const artistHref = - this.props.notification.artistHref || extractNodes(this.props.notification.artworks)[0]?.artists?.[0]?.href + this.props.notification.artistHref || + extractNodes(this.props.notification.artworks)[0]?.artists?.[0]?.href if (artistHref) { navigate(artistHref) } diff --git a/src/lib/Containers/BidFlow.tsx b/src/lib/Containers/BidFlow.tsx index 405d082f5e4..8dcb7e36cea 100644 --- a/src/lib/Containers/BidFlow.tsx +++ b/src/lib/Containers/BidFlow.tsx @@ -5,7 +5,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context" import { TimeOffsetProvider } from "../Components/Bidding/Context/TimeOffsetProvider" import { SelectMaxBidQueryRenderer } from "../Components/Bidding/Screens/SelectMaxBid" -export const BidFlow: React.FC, "navigator">> = (props) => { +export const BidFlow: React.FC< + Omit, "navigator"> +> = (props) => { return ( diff --git a/src/lib/Containers/Inbox/Inbox.tsx b/src/lib/Containers/Inbox/Inbox.tsx index 746b2f1a484..14ad98f3b38 100644 --- a/src/lib/Containers/Inbox/Inbox.tsx +++ b/src/lib/Containers/Inbox/Inbox.tsx @@ -128,9 +128,16 @@ export class Inbox extends React.Component { onChangeTab={({ i }: { i: number }) => this.handleNavigationTab(i)} > - + - + { const hasBids = !!lotStanding && lotStanding.length > 0 const hasConversations = !!conversationsExistenceCheck && conversationsExistenceCheck.length > 0 return hasBids || hasConversations ? ( - }> - (this.activeBids = activeBids)} /> + + } + > + (this.activeBids = activeBids)} + /> { it("Shows a zero state when there are no bids/conversations", () => { const tree = JSON.stringify( - renderWithLayout(, { width: 768, height: 1024 }) + renderWithLayout(, { + width: 768, + height: 1024, + }) ) // Taken from the title in ZeroStateInbox expect(tree).toContain("Buying art on Artsy is simple") @@ -70,7 +73,8 @@ const meProps = (withBids: boolean = true, withMessages: boolean = true) => { artist_names: "Bradley Theodore", image: { url: "https://d32dm0rphc51dk.cloudfront.net/bJ9I_vJX9ksaKFJAkOAIKg/normalized.jpg", - image_url: "https://d32dm0rphc51dk.cloudfront.net/bJ9I_vJX9ksaKFJAkOAIKg/:version.jpg", + image_url: + "https://d32dm0rphc51dk.cloudfront.net/bJ9I_vJX9ksaKFJAkOAIKg/:version.jpg", }, }, }, @@ -99,7 +103,8 @@ const meProps = (withBids: boolean = true, withMessages: boolean = true) => { artist_names: "Aida Muluneh", image: { url: "https://d32dm0rphc51dk.cloudfront.net/FDIuqbZUY1kLR-1Pd-Ec8w/normalized.jpg", - image_url: "https://d32dm0rphc51dk.cloudfront.net/FDIuqbZUY1kLR-1Pd-Ec8w/:version.jpg", + image_url: + "https://d32dm0rphc51dk.cloudfront.net/FDIuqbZUY1kLR-1Pd-Ec8w/:version.jpg", }, }, }, @@ -136,7 +141,8 @@ const meProps = (withBids: boolean = true, withMessages: boolean = true) => { id: "josephine-meckseper-untitled-flag-2-2017", title: "Untitled (Flag 2), 2017", image: { - image_url: "https://d32dm0rphc51dk.cloudfront.net/3N6jyj5G_jjzYbkwbIM4tA/:version.jpg", + image_url: + "https://d32dm0rphc51dk.cloudfront.net/3N6jyj5G_jjzYbkwbIM4tA/:version.jpg", }, artist: { name: "Josephine Meckseper", @@ -169,7 +175,8 @@ const meProps = (withBids: boolean = true, withMessages: boolean = true) => { id: "robert-longo-untitled-dividing-time", title: "Untitled (Dividing Time)", image: { - image_url: "https://d32dm0rphc51dk.cloudfront.net/4GlhFa7ci5-0W25sjDNFIQ/:version.jpg", + image_url: + "https://d32dm0rphc51dk.cloudfront.net/4GlhFa7ci5-0W25sjDNFIQ/:version.jpg", }, artist: { name: "Robert Longo", @@ -202,7 +209,8 @@ const meProps = (withBids: boolean = true, withMessages: boolean = true) => { id: "trevor-paglen-weeping-angel", title: "Weeping Angel", image: { - image_url: "https://d32dm0rphc51dk.cloudfront.net/W-XblMAGxZJbhx0FfH1HtQ/:version.jpg", + image_url: + "https://d32dm0rphc51dk.cloudfront.net/W-XblMAGxZJbhx0FfH1HtQ/:version.jpg", }, artist: { name: "Trevor Paglen", diff --git a/src/lib/Containers/Inquiry.tsx b/src/lib/Containers/Inquiry.tsx index 6b0b47475c2..cb0fd744ee9 100644 --- a/src/lib/Containers/Inquiry.tsx +++ b/src/lib/Containers/Inquiry.tsx @@ -209,7 +209,9 @@ export class Inquiry extends React.Component { value={message || undefined} keyboardAppearance="dark" multiline - autoFocus={typeof jest === "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */} + autoFocus={ + typeof jest === "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */ + } onEndEditing={() => { this.setState({ text: null }) }} diff --git a/src/lib/Containers/WorksForYou.tests.tsx b/src/lib/Containers/WorksForYou.tests.tsx index 2e55211e115..6b51b0f3214 100644 --- a/src/lib/Containers/WorksForYou.tests.tsx +++ b/src/lib/Containers/WorksForYou.tests.tsx @@ -95,7 +95,10 @@ const notificationsResponse = () => { artists: "Ana Mendieta", summary: "2 Works Added", artworks: { - edges: [{ node: { title: "Corazón de Roca con Sangre" } }, { node: { title: "Butterfly" } }], + edges: [ + { node: { title: "Corazón de Roca con Sangre" } }, + { node: { title: "Butterfly" } }, + ], }, image: { resized: { diff --git a/src/lib/Containers/WorksForYou.tsx b/src/lib/Containers/WorksForYou.tsx index f3b1da62437..3e975464631 100644 --- a/src/lib/Containers/WorksForYou.tsx +++ b/src/lib/Containers/WorksForYou.tsx @@ -89,7 +89,9 @@ export class WorksForYou extends React.Component { item.id} - refreshControl={} + refreshControl={ + + } onLayout={(event) => { this.setState({ width: event.nativeEvent.layout.width }) }} @@ -140,8 +142,11 @@ export const WorksForYouContainer = createPaginationContainer( sort: { type: "ArtworkSorts", defaultValue: PUBLISHED_AT_DESC } ) { followsAndSaves { - notifications: bundledArtworksByArtistConnection(sort: $sort, first: $count, after: $cursor) - @connection(key: "WorksForYou_notifications") { + notifications: bundledArtworksByArtistConnection( + sort: $sort + first: $count + after: $cursor + ) @connection(key: "WorksForYou_notifications") { pageInfo { hasNextPage endCursor diff --git a/src/lib/ErrorReporting.ts b/src/lib/ErrorReporting.ts index 49a432ad10f..b5903f9dbab 100644 --- a/src/lib/ErrorReporting.ts +++ b/src/lib/ErrorReporting.ts @@ -4,7 +4,10 @@ import Config from "react-native-config" import { sentryReleaseName } from "../../app.json" import { GlobalStore, useFeatureFlag } from "./store/GlobalStore" -export const setupSentry = (props: Partial = {}, captureExceptions = !__DEV__) => { +export const setupSentry = ( + props: Partial = {}, + captureExceptions = !__DEV__ +) => { if (!captureExceptions && Config.SENTRY_DSN) { Sentry.init({ dsn: Config.SENTRY_DSN, diff --git a/src/lib/Icons/TriangleDown.tsx b/src/lib/Icons/TriangleDown.tsx index f2b0528a920..a6da2e3ff1b 100644 --- a/src/lib/Icons/TriangleDown.tsx +++ b/src/lib/Icons/TriangleDown.tsx @@ -5,7 +5,12 @@ import Svg, { Path } from "react-native-svg" export const TriangleDown: React.FC = (props) => { return ( - + ) } diff --git a/src/lib/NativeModules/ARScreenPresenterModule.tsx b/src/lib/NativeModules/ARScreenPresenterModule.tsx index f5036a6c1e5..aba4db911e9 100644 --- a/src/lib/NativeModules/ARScreenPresenterModule.tsx +++ b/src/lib/NativeModules/ARScreenPresenterModule.tsx @@ -1,4 +1,9 @@ -import { NavigationContainerRef, NavigationState, StackActions, TabActions } from "@react-navigation/native" +import { + NavigationContainerRef, + NavigationState, + StackActions, + TabActions, +} from "@react-navigation/native" import immer from "immer-peasy" import { ViewDescriptor } from "lib/navigation/navigate" import { BottomTabType } from "lib/Scenes/BottomTabs/BottomTabType" @@ -34,12 +39,15 @@ function updateNavigationState(updater: (draft: Mutable) => voi const nextState = immer(currentState, updater) __unsafe_mainModalStackRef.current?.resetRoot(nextState) } -function updateTabStackState(tab: BottomTabType, updater: (draft: Mutable) => void) { +function updateTabStackState( + tab: BottomTabType, + updater: (draft: Mutable) => void +) { updateNavigationState((state) => { const tabs = state.routes[0].state?.routes - const tabState = (tabs as Array<{ name: BottomTabType; state: Mutable }>)?.find( - (x) => x.name === tab - )?.state + const tabState = ( + tabs as Array<{ name: BottomTabType; state: Mutable }> + )?.find((x) => x.name === tab)?.state if (!tabState) { console.error("unable to find tab state for tab", tab, state) return @@ -85,7 +93,10 @@ export const ARScreenPresenterModule: typeof NativeModules["ARScreenPresenterMod ) } else { __unsafe_mainModalStackRef.current?.dispatch( - StackActions.push("modal", { rootModuleName: viewDescriptor.moduleName, rootModuleProps: viewDescriptor.props }) + StackActions.push("modal", { + rootModuleName: viewDescriptor.moduleName, + rootModuleProps: viewDescriptor.props, + }) ) } }, diff --git a/src/lib/NativeModules/ArtsyNativeModule.tsx b/src/lib/NativeModules/ArtsyNativeModule.tsx index abb6b974972..04a79085d2f 100644 --- a/src/lib/NativeModules/ArtsyNativeModule.tsx +++ b/src/lib/NativeModules/ArtsyNativeModule.tsx @@ -43,5 +43,8 @@ export const ArtsyNativeModule = { } : NativeModules.ArtsyNativeModule.lockActivityScreenOrientation, gitCommitShortHash: NativeModules.ArtsyNativeModule.gitCommitShortHash, - isBetaOrDev: Platform.OS === "ios" ? NativeModules.ArtsyNativeModule.isBetaOrDev : appJson().isAndroidBeta || __DEV__, + isBetaOrDev: + Platform.OS === "ios" + ? NativeModules.ArtsyNativeModule.isBetaOrDev + : appJson().isAndroidBeta || __DEV__, } diff --git a/src/lib/NativeModules/LegacyNativeModules.tsx b/src/lib/NativeModules/LegacyNativeModules.tsx index 4cd00e0e09b..ab0e1bd0c46 100644 --- a/src/lib/NativeModules/LegacyNativeModules.tsx +++ b/src/lib/NativeModules/LegacyNativeModules.tsx @@ -6,7 +6,8 @@ import type { Image as RNCImage } from "react-native-image-crop-picker" import { getLocales, getTimeZone } from "react-native-localize" import { ARScreenPresenterModule } from "./ARScreenPresenterModule" -const noop: any = (name: string) => () => console.warn(`method ${name} doesn't exist on android yet`) +const noop: any = (name: string) => () => + console.warn(`method ${name} doesn't exist on android yet`) /** * This file is a gateway to our iOS-specific native modules that either @@ -22,7 +23,9 @@ interface LegacyNativeModules { ARTemporaryAPIModule: { requestPrepromptNotificationPermissions(): void requestDirectNotificationPermissions(): void - fetchNotificationPermissions(callback: (error: any, result: PushAuthorizationStatus) => void): void + fetchNotificationPermissions( + callback: (error: any, result: PushAuthorizationStatus) => void + ): void markNotificationsRead(callback: (error?: Error) => any): void setApplicationIconBadgeNumber(n: number): void getUserEmail(): string @@ -62,7 +65,12 @@ interface LegacyNativeModules { popStack(stackID: string): void popToRootOrScrollToTop(stackID: string): void popToRootAndScrollToTop(stackID: string): Promise - presentMediaPreviewController(reactTag: number, route: string, mimeType: string, cacheKey: string): void + presentMediaPreviewController( + reactTag: number, + route: string, + mimeType: string, + cacheKey: string + ): void presentEmailComposerWithBody(body: string, subject: string, toAddress: string): void presentEmailComposerWithSubject(subject: string, toAddress: string): void presentAugmentedRealityVIR( diff --git a/src/lib/NativeModules/NotificationsManager.tsx b/src/lib/NativeModules/NotificationsManager.tsx index 61b3fc9ecab..2caa17a99b3 100644 --- a/src/lib/NativeModules/NotificationsManager.tsx +++ b/src/lib/NativeModules/NotificationsManager.tsx @@ -1,4 +1,6 @@ import { NativeEventEmitter } from "react-native" import { LegacyNativeModules } from "./LegacyNativeModules" -export const NotificationsManager = new NativeEventEmitter(LegacyNativeModules.ARNotificationsManager as any) +export const NotificationsManager = new NativeEventEmitter( + LegacyNativeModules.ARNotificationsManager as any +) diff --git a/src/lib/NativeModules/presentEmailComposer.ts b/src/lib/NativeModules/presentEmailComposer.ts index c583bba95c9..a5d503783ad 100644 --- a/src/lib/NativeModules/presentEmailComposer.ts +++ b/src/lib/NativeModules/presentEmailComposer.ts @@ -6,7 +6,11 @@ export function presentEmailComposer(toAddress: string, subject: string, body?: if (Platform.OS !== "ios") { Linking.openURL(`mailto:${toAddress}?${stringify({ subject, body })}`) } else if (body) { - LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithBody(body, subject, toAddress) + LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithBody( + body, + subject, + toAddress + ) } else { LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithSubject(subject, toAddress) } diff --git a/src/lib/NativeModules/triggerCamera.tsx b/src/lib/NativeModules/triggerCamera.tsx index 74a698313b2..d8e6e5b62e5 100644 --- a/src/lib/NativeModules/triggerCamera.tsx +++ b/src/lib/NativeModules/triggerCamera.tsx @@ -6,7 +6,9 @@ export async function triggerCamera(component: React.Component): Promi try { reactTag = findNodeHandle(component) } catch (err) { - console.error("could not find tag for the component calling ARTakeCameraPhotoModule.triggerCameraModal") + console.error( + "could not find tag for the component calling ARTakeCameraPhotoModule.triggerCameraModal" + ) return } return LegacyNativeModules.ARTakeCameraPhotoModule.triggerCameraModal(reactTag) diff --git a/src/lib/Scenes/About/About.tsx b/src/lib/Scenes/About/About.tsx index 510efc24184..765b162d14c 100644 --- a/src/lib/Scenes/About/About.tsx +++ b/src/lib/Scenes/About/About.tsx @@ -14,7 +14,9 @@ export const About: React.FC = () => { const appVersion = getVersion() const toast = useToast() const [tapCount, updateTapCount] = useState(0) - const { value: userIsDev, flipValue: userIsDevFlipValue } = GlobalStore.useAppState((store) => store.config.userIsDev) + const { value: userIsDev, flipValue: userIsDevFlipValue } = GlobalStore.useAppState( + (store) => store.config.userIsDev + ) useEffect(() => { const flip = (userIsDev && tapCount >= 3) || (!userIsDev && tapCount >= 7) @@ -45,13 +47,18 @@ export const About: React.FC = () => { navigate("/terms", { modal: true })} /> navigate("/privacy", { modal: true })} /> - navigate("/conditions-of-sale", { modal: true })} /> + navigate("/conditions-of-sale", { modal: true })} + /> updateTapCount((count) => count + 1)} chevron={false} - style={userIsDev ? { borderRightColor: color("devpurple"), borderRightWidth: 1 } : undefined} + style={ + userIsDev ? { borderRightColor: color("devpurple"), borderRightWidth: 1 } : undefined + } /> diff --git a/src/lib/Scenes/Articles/Articles.tsx b/src/lib/Scenes/Articles/Articles.tsx index de7229d9723..c3bcbb913c1 100644 --- a/src/lib/Scenes/Articles/Articles.tsx +++ b/src/lib/Scenes/Articles/Articles.tsx @@ -73,8 +73,12 @@ const articlesConnectionFragment = graphql` sort: { type: "ArticleSorts" } inEditorialFeed: { type: "Boolean" } ) { - articlesConnection(first: $count, after: $after, sort: $sort, inEditorialFeed: $inEditorialFeed) - @connection(key: "Articles_articlesConnection") { + articlesConnection( + first: $count + after: $after + sort: $sort + inEditorialFeed: $inEditorialFeed + ) @connection(key: "Articles_articlesConnection") { edges { cursor node { diff --git a/src/lib/Scenes/Articles/ArticlesList.tsx b/src/lib/Scenes/Articles/ArticlesList.tsx index 99fc88e15b2..5f46b79f310 100644 --- a/src/lib/Scenes/Articles/ArticlesList.tsx +++ b/src/lib/Scenes/Articles/ArticlesList.tsx @@ -1,7 +1,11 @@ import { ActionType, ContextModule, OwnerType } from "@artsy/cohesion" import { ArticleCard_article } from "__generated__/ArticleCard_article.graphql" import { ArticleCardContainer } from "lib/Components/ArticleCard" -import { PlaceholderBox, ProvidePlaceholderContext, RandomWidthPlaceholderText } from "lib/utils/placeholders" +import { + PlaceholderBox, + ProvidePlaceholderContext, + RandomWidthPlaceholderText, +} from "lib/utils/placeholders" import { ProvideScreenTrackingWithCohesionSchema } from "lib/utils/track" import { screen } from "lib/utils/track/helpers" import { useScreenDimensions } from "lib/utils/useScreenDimensions" @@ -131,7 +135,12 @@ export const ArticlesPlaceholder = () => { - + diff --git a/src/lib/Scenes/Artist/Artist.tsx b/src/lib/Scenes/Artist/Artist.tsx index ea9bd0ddf77..dd38d3f2da4 100644 --- a/src/lib/Scenes/Artist/Artist.tsx +++ b/src/lib/Scenes/Artist/Artist.tsx @@ -42,7 +42,13 @@ interface ArtistProps { } export const Artist: React.FC = (props) => { - const { artistAboveTheFold, artistBelowTheFold, initialTab = INITIAL_TAB, searchCriteria, fetchCriteriaError } = props + const { + artistAboveTheFold, + artistBelowTheFold, + initialTab = INITIAL_TAB, + searchCriteria, + fetchCriteriaError, + } = props const popoverMessage = usePopoverMessage() const tabs: TabProps[] = [] @@ -65,7 +71,11 @@ export const Artist: React.FC = (props) => { if (displayAboutSection) { tabs.push({ title: "Overview", - content: artistBelowTheFold ? : , + content: artistBelowTheFold ? ( + + ) : ( + + ), }) } @@ -80,7 +90,9 @@ export const Artist: React.FC = (props) => { tabs.push({ title: "Insights", content: artistBelowTheFold ? ( - (tabIndex: number) => + (tabIndex: number) => ( + + ) ) : ( ), @@ -93,8 +105,8 @@ export const Artist: React.FC = (props) => { content: ( - There aren’t any works available by the artist at this time. Follow to receive notifications when new works - are added. + There aren’t any works available by the artist at this time. Follow to receive + notifications when new works are added. ), @@ -119,7 +131,9 @@ export const Artist: React.FC = (props) => { } tabs={tabs} - bottomContent={} + bottomContent={ + + } disableBackButtonUpdate /> @@ -127,7 +141,9 @@ export const Artist: React.FC = (props) => { ) } -interface ArtistQueryRendererProps extends ArtistAboveTheFoldQueryVariables, ArtistBelowTheFoldQueryVariables { +interface ArtistQueryRendererProps + extends ArtistAboveTheFoldQueryVariables, + ArtistBelowTheFoldQueryVariables { environment?: RelayModernEnvironment initialTab?: string searchCriteriaID?: string @@ -173,7 +189,9 @@ export const ArtistQueryRenderer: React.FC = (props) = renderPlaceholder: () => , renderComponent: (searchCriteriaProps) => { const { savedSearchCriteria, fetchCriteriaError } = searchCriteriaProps - const preparedSavedSearchCriteria = getOnlyFilledSearchCriteriaValues(savedSearchCriteria ?? {}) + const preparedSavedSearchCriteria = getOnlyFilledSearchCriteriaValues( + savedSearchCriteria ?? {} + ) const initialArtworksInput = { ...defaultArtistVariables().input, sort: !!savedSearchCriteria ? "-published_at" : DEFAULT_ARTWORK_SORT.paramValue, diff --git a/src/lib/Scenes/Artist/ArtistSavedSearch.tests.tsx b/src/lib/Scenes/Artist/ArtistSavedSearch.tests.tsx index df0dac9bbf0..a8ce5c56ad7 100644 --- a/src/lib/Scenes/Artist/ArtistSavedSearch.tests.tsx +++ b/src/lib/Scenes/Artist/ArtistSavedSearch.tests.tsx @@ -49,7 +49,11 @@ describe("Saved search banner on artist screen", () => { const getTree = (searchCriteriaID?: string) => { return renderWithWrappersTL( - + ) } diff --git a/src/lib/Scenes/Artist/SearchCriteria.tests.tsx b/src/lib/Scenes/Artist/SearchCriteria.tests.tsx index 6f407c76649..dff1d1c57e6 100644 --- a/src/lib/Scenes/Artist/SearchCriteria.tests.tsx +++ b/src/lib/Scenes/Artist/SearchCriteria.tests.tsx @@ -18,7 +18,9 @@ describe("SearchCriteria", () => { const mockRenderComponent = jest.fn(() => <>) renderWithWrappersTL( - + ) expect(mockRenderComponent).toBeCalledWith({ diff --git a/src/lib/Scenes/Artist/SearchCriteria.tsx b/src/lib/Scenes/Artist/SearchCriteria.tsx index 5d9e7df3dc8..d5286b65a45 100644 --- a/src/lib/Scenes/Artist/SearchCriteria.tsx +++ b/src/lib/Scenes/Artist/SearchCriteria.tsx @@ -58,7 +58,8 @@ export const SearchCriteriaQueryRenderer: React.FC{renderPlaceholder()} } - const savedSearchCriteria = (relayProps?.me?.savedSearch as SearchCriteriaAttributes) ?? null + const savedSearchCriteria = + (relayProps?.me?.savedSearch as SearchCriteriaAttributes) ?? null return renderComponent({ fetchCriteriaError: error, diff --git a/src/lib/Scenes/ArtistArticles/ArtistArticles.tsx b/src/lib/Scenes/ArtistArticles/ArtistArticles.tsx index 769dbf06692..4fd6e6b0b8a 100644 --- a/src/lib/Scenes/ArtistArticles/ArtistArticles.tsx +++ b/src/lib/Scenes/ArtistArticles/ArtistArticles.tsx @@ -59,8 +59,12 @@ export const ArtistArticlesContainer = createPaginationContainer( @argumentDefinitions(count: { type: "Int", defaultValue: 10 }, cursor: { type: "String" }) { internalID name - articlesConnection(first: $count, after: $cursor, sort: PUBLISHED_AT_DESC, inEditorialFeed: true) - @connection(key: "ArtistArticles_articlesConnection") { + articlesConnection( + first: $count + after: $cursor + sort: PUBLISHED_AT_DESC + inEditorialFeed: true + ) @connection(key: "ArtistArticles_articlesConnection") { edges { cursor node { diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeries.tests.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeries.tests.tsx index d8f1dc3db5e..d3e7ff7b86f 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeries.tests.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeries.tests.tsx @@ -51,7 +51,9 @@ describe("Artist Series Rail", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeries.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeries.tsx index 3e1a368aae5..7a28938c5c3 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeries.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeries.tsx @@ -12,7 +12,10 @@ import { Box, Flex, Separator, Spacer, Text } from "palette" import React, { useState } from "react" import { ArtworkFilterNavigator, FilterModalMode } from "lib/Components/ArtworkFilter" -import { ArtworkFiltersStoreProvider, ArtworksFiltersStore } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersStoreProvider, + ArtworksFiltersStore, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { useSelectedFiltersCount } from "lib/Components/ArtworkFilter/useArtworkFilters" import { ArtworksFilterHeader } from "lib/Components/ArtworkGrids/ArtworksFilterHeader" import { PlaceholderBox, PlaceholderGrid, PlaceholderText } from "lib/utils/placeholders" @@ -101,7 +104,10 @@ export const ArtistSeries: React.FC = (props) => { ) : undefined } stickyHeaderContent={ - + } > @@ -166,7 +172,9 @@ const ArtistSeriesPlaceholder: React.FC<{}> = ({}) => { ) } -export const ArtistSeriesQueryRenderer: React.FC<{ artistSeriesID: string }> = ({ artistSeriesID }) => { +export const ArtistSeriesQueryRenderer: React.FC<{ artistSeriesID: string }> = ({ + artistSeriesID, +}) => { return ( diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tests.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tests.tsx index 164380913c1..78c160ea9e4 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tests.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tests.tsx @@ -47,7 +47,9 @@ describe("Artist Series Artworks", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -70,6 +72,8 @@ describe("Artist Series Artworks", () => { expect(tree.root.findAllByType(InfiniteScrollArtworksGridContainer)).toHaveLength(0) expect(tree.root.findAllByType(FilteredArtworkGridZeroState)).toHaveLength(1) - expect(extractText(tree.root)).toContain("No results found\nPlease try another search.Clear filtersClear filters") + expect(extractText(tree.root)).toContain( + "No results found\nPlease try another search.Clear filtersClear filters" + ) }) }) diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tsx index 5f42d707bfb..577444efd7e 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesArtworks.tsx @@ -18,13 +18,18 @@ interface ArtistSeriesArtworksProps { const PAGE_SIZE = 20 -export const ArtistSeriesArtworks: React.FC = ({ artistSeries, relay }) => { +export const ArtistSeriesArtworks: React.FC = ({ + artistSeries, + relay, +}) => { const tracking = useTracking() const artworks = artistSeries?.artistSeriesArtworks! const artworksTotal = artworks?.counts?.total ?? 0 - const setFiltersCountAction = ArtworksFiltersStore.useStoreActions((state) => state.setFiltersCountAction) + const setFiltersCountAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setFiltersCountAction + ) useArtworkFilters({ relay, @@ -54,7 +59,11 @@ export const ArtistSeriesArtworks: React.FC = ({ arti if (artworksTotal === 0) { return ( - + ) @@ -152,7 +161,8 @@ export const ArtistSeriesArtworksFragmentContainer = createPaginationContainer( $input: FilterArtworksInput ) { artistSeries(id: $id) { - ...ArtistSeriesArtworks_artistSeries @arguments(count: $count, cursor: $cursor, input: $input) + ...ArtistSeriesArtworks_artistSeries + @arguments(count: $count, cursor: $cursor, input: $input) } } `, diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tests.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tests.tsx index 37e40412b3d..1fb1127aacd 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tests.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tests.tsx @@ -90,84 +90,85 @@ describe("Full Artist Series List", () => { }) }) -const ArtistSeriesFullArtistSeriesListFixture: ArtistSeriesFullArtistSeriesListTestsQueryRawResponse = { - artist: { - id: "yayoi-kusama", - artistSeriesConnection: { - edges: [ - { - node: { - featured: true, - slug: "yayoi-kusama-plums", - internalID: "da821a13-92fc-49c2-bbd5-bebb790f7020", - title: "plums", - artworksCountMessage: "40 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/bLKO-OQg8UOzKuKcKxXeWQ/main.jpg", +const ArtistSeriesFullArtistSeriesListFixture: ArtistSeriesFullArtistSeriesListTestsQueryRawResponse = + { + artist: { + id: "yayoi-kusama", + artistSeriesConnection: { + edges: [ + { + node: { + featured: true, + slug: "yayoi-kusama-plums", + internalID: "da821a13-92fc-49c2-bbd5-bebb790f7020", + title: "plums", + artworksCountMessage: "40 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/bLKO-OQg8UOzKuKcKxXeWQ/main.jpg", + }, }, }, - }, - { - node: { - featured: false, - slug: "yayoi-kusama-apricots", - internalID: "ecfa5731-9d64-4bc2-9f9f-c427a9126064", - title: "apricots", - artworksCountMessage: "35 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/Oymspr9llGzRC-lTZA8htA/main.jpg", + { + node: { + featured: false, + slug: "yayoi-kusama-apricots", + internalID: "ecfa5731-9d64-4bc2-9f9f-c427a9126064", + title: "apricots", + artworksCountMessage: "35 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/Oymspr9llGzRC-lTZA8htA/main.jpg", + }, }, }, - }, - { - node: { - featured: false, - slug: "yayoi-kusama-pumpkins", - internalID: "58597ef5-3390-406b-b6d2-d4e308125d0d", - title: "Pumpkins", - artworksCountMessage: "25 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/dL3hz4h6f_tMHQjVHsdO4w/medium.jpg", + { + node: { + featured: false, + slug: "yayoi-kusama-pumpkins", + internalID: "58597ef5-3390-406b-b6d2-d4e308125d0d", + title: "Pumpkins", + artworksCountMessage: "25 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/dL3hz4h6f_tMHQjVHsdO4w/medium.jpg", + }, }, }, - }, - { - node: { - featured: false, - slug: "yayoi-kusama-apples", - internalID: "5856ee51-35eb-4b75-bb12-15a1cd7e012e", - title: "apples", - artworksCountMessage: "15 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + { + node: { + featured: false, + slug: "yayoi-kusama-apples", + internalID: "5856ee51-35eb-4b75-bb12-15a1cd7e012e", + title: "apples", + artworksCountMessage: "15 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + }, }, }, - }, - { - node: { - featured: false, - slug: "yayoi-kusama-grapefruit", - internalID: "5856ee51-35eb-4b75-bb12-15a1816a9", - title: "grapefruit", - artworksCountMessage: "10 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + { + node: { + featured: false, + slug: "yayoi-kusama-grapefruit", + internalID: "5856ee51-35eb-4b75-bb12-15a1816a9", + title: "grapefruit", + artworksCountMessage: "10 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + }, }, }, - }, - { - node: { - featured: false, - slug: "yayoi-kusama-dragonfruit", - internalID: "5856ee51-35eb-4b75-bb12-15a1cd18161", - title: "dragonfruit", - artworksCountMessage: "8 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + { + node: { + featured: false, + slug: "yayoi-kusama-dragonfruit", + internalID: "5856ee51-35eb-4b75-bb12-15a1cd18161", + title: "dragonfruit", + artworksCountMessage: "8 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + }, }, }, - }, - ], + ], + }, }, - }, -} + } diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tsx index 7cdeea38862..61c8fef0a77 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesFullArtistSeriesList.tsx @@ -50,28 +50,33 @@ export const FullArtistSeriesList: React.FC = ({ arti ) } -export const ArtistSeriesFullArtistSeriesListFragmentContainer = createFragmentContainer(FullArtistSeriesList, { - artist: graphql` - fragment ArtistSeriesFullArtistSeriesList_artist on Artist { - artistSeriesConnection(first: 50) { - edges { - node { - slug - internalID - title - featured - artworksCountMessage - image { - url +export const ArtistSeriesFullArtistSeriesListFragmentContainer = createFragmentContainer( + FullArtistSeriesList, + { + artist: graphql` + fragment ArtistSeriesFullArtistSeriesList_artist on Artist { + artistSeriesConnection(first: 50) { + edges { + node { + slug + internalID + title + featured + artworksCountMessage + image { + url + } } } } } - } - `, -}) + `, + } +) -export const ArtistSeriesFullArtistSeriesListQueryRenderer: React.FC<{ artistID: string }> = ({ artistID }) => { +export const ArtistSeriesFullArtistSeriesListQueryRenderer: React.FC<{ artistID: string }> = ({ + artistID, +}) => { return ( environment={defaultEnvironment} diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesHeader.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesHeader.tsx index 116b99d6a82..91e497c162e 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesHeader.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesHeader.tsx @@ -12,7 +12,12 @@ export const ArtistSeriesHeader: React.FC = ({ artistSe return ( - + ) } diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesListItem.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesListItem.tsx index 899c7ad8494..99d6ec4a678 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesListItem.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesListItem.tsx @@ -1,4 +1,10 @@ -import { ActionType, ContextModule, OwnerType, ScreenOwnerType, TappedArtistSeriesGroup } from "@artsy/cohesion" +import { + ActionType, + ContextModule, + OwnerType, + ScreenOwnerType, + TappedArtistSeriesGroup, +} from "@artsy/cohesion" import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView" import { navigate } from "lib/navigation/navigate" import { ArtistSeriesConnectionEdge } from "lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries" diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tests.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tests.tsx index 373695f7203..4b31e6d3ea0 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tests.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tests.tsx @@ -3,7 +3,10 @@ import { ArtistSeriesMetaTestsQueryRawResponse, } from "__generated__/ArtistSeriesMetaTestsQuery.graphql" import { navigate } from "lib/navigation/navigate" -import { ArtistSeriesMeta, ArtistSeriesMetaFragmentContainer } from "lib/Scenes/ArtistSeries/ArtistSeriesMeta" +import { + ArtistSeriesMeta, + ArtistSeriesMetaFragmentContainer, +} from "lib/Scenes/ArtistSeries/ArtistSeriesMeta" import { mockTrackEvent } from "lib/tests/globallyMockedStuff" import { renderWithWrappers } from "lib/tests/renderWithWrappers" import { EntityHeader } from "palette" @@ -67,7 +70,9 @@ describe("Artist Series Meta", () => { it("renders the Artist Series title", () => { const wrapper = getWrapper() - expect(wrapper.root.findByProps({ testID: "title" }).props.children).toBe("These are the Pumpkins") + expect(wrapper.root.findByProps({ testID: "title" }).props.children).toBe( + "These are the Pumpkins" + ) }) it("renders the Artist Series description", () => { @@ -91,7 +96,9 @@ describe("Artist Series Meta", () => { it("tracks unfollows", () => { const wrapper = getWrapper() - const followButton = wrapper.root.findAllByType(EntityHeader)[0].findAllByType(TouchableWithoutFeedback)[0] + const followButton = wrapper.root + .findAllByType(EntityHeader)[0] + .findAllByType(TouchableWithoutFeedback)[0] followButton.props.onPress() expect(mockTrackEvent).toHaveBeenCalledWith({ action: "unfollowedArtist", diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tsx index a89f3583a87..06d6429fdde 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesMeta.tsx @@ -1,4 +1,10 @@ -import { ContextModule, FollowedArgs, followedArtist, OwnerType, unfollowedArtist } from "@artsy/cohesion" +import { + ContextModule, + FollowedArgs, + followedArtist, + OwnerType, + unfollowedArtist, +} from "@artsy/cohesion" import { ArtistSeriesMeta_artistSeries } from "__generated__/ArtistSeriesMeta_artistSeries.graphql" import { ArtistSeriesMetaFollowMutation } from "__generated__/ArtistSeriesMetaFollowMutation.graphql" import { ReadMore } from "lib/Components/ReadMore" @@ -15,7 +21,9 @@ interface ArtistSeriesMetaProps { relay: RelayProp } -type ArtistToFollowOrUnfollow = NonNullable[0]> +type ArtistToFollowOrUnfollow = NonNullable< + NonNullable[0] +> export const ArtistSeriesMeta: React.FC = ({ artistSeries, relay }) => { const metaRef = useRef(null) @@ -102,7 +110,11 @@ export const ArtistSeriesMeta: React.FC = ({ artistSeries )} - + ) } diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tests.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tests.tsx index 9ec2d2f4f73..7bd910ff74e 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tests.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tests.tsx @@ -92,7 +92,9 @@ describe("ArtistSeriesMoreSeries", () => { it("tracks an event on click", () => { const wrapper = getWrapper(ArtistSeriesMoreSeriesFixture) - const artistSeriesButton = wrapper.root.findAllByType(ArtistSeriesListItem)[0].findByType(Touchable) + const artistSeriesButton = wrapper.root + .findAllByType(ArtistSeriesListItem)[0] + .findByType(Touchable) act(() => artistSeriesButton.props.onPress()) @@ -227,55 +229,56 @@ const ArtistSeriesMoreSeriesFixture: ArtistSeriesMoreSeriesTestsQueryRawResponse }, } -const ArtistSeriesMoreSeriesBelowViewAllThresholdFixture: ArtistSeriesMoreSeriesTestsQueryRawResponse = { - artistSeries: { - artist: [ - { - id: "abc123", - internalID: "jahfadf981", - slug: "yayoi-kusama", - artistSeriesConnection: { - totalCount: 3, - edges: [ - { - node: { - featured: true, - slug: "yayoi-kusama-pumpkins", - internalID: "58597ef5-3390-406b-b6d2-d4e308125d0d", - title: "Pumpkins", - artworksCountMessage: "25 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/dL3hz4h6f_tMHQjVHsdO4w/medium.jpg", +const ArtistSeriesMoreSeriesBelowViewAllThresholdFixture: ArtistSeriesMoreSeriesTestsQueryRawResponse = + { + artistSeries: { + artist: [ + { + id: "abc123", + internalID: "jahfadf981", + slug: "yayoi-kusama", + artistSeriesConnection: { + totalCount: 3, + edges: [ + { + node: { + featured: true, + slug: "yayoi-kusama-pumpkins", + internalID: "58597ef5-3390-406b-b6d2-d4e308125d0d", + title: "Pumpkins", + artworksCountMessage: "25 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/dL3hz4h6f_tMHQjVHsdO4w/medium.jpg", + }, }, }, - }, - { - node: { - featured: true, - slug: "yayoi-kusama-apples", - internalID: "5856ee51-35eb-4b75-bb12-15a1cd7e012e", - title: "apples", - artworksCountMessage: "4 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + { + node: { + featured: true, + slug: "yayoi-kusama-apples", + internalID: "5856ee51-35eb-4b75-bb12-15a1cd7e012e", + title: "apples", + artworksCountMessage: "4 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + }, }, }, - }, - { - node: { - featured: true, - slug: "yayoi-kusama-dragonfruit", - internalID: "5856ee51-35eb-4b75-bb12-15a1cd18161", - title: "dragonfruit", - artworksCountMessage: "8 available", - image: { - url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + { + node: { + featured: true, + slug: "yayoi-kusama-dragonfruit", + internalID: "5856ee51-35eb-4b75-bb12-15a1cd18161", + title: "dragonfruit", + artworksCountMessage: "8 available", + image: { + url: "https://d32dm0rphc51dk.cloudfront.net/Nv63KiPQo91g2-W2V3lgAw/main.jpg", + }, }, }, - }, - ], + ], + }, }, - }, - ], - }, -} + ], + }, + } diff --git a/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tsx b/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tsx index bf505269e81..c431e3305b1 100644 --- a/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tsx +++ b/src/lib/Scenes/ArtistSeries/ArtistSeriesMoreSeries.tsx @@ -35,7 +35,8 @@ export const ArtistSeriesMoreSeries: React.FC = ({ const series = artist?.artistSeriesConnection?.edges ?? [] const [artistSeries, setArtistSeries] = useState(series) const excludedArtistSeriesCount = currentArtistSeriesExcluded ? 1 : 0 - const totalCount = Number(artist?.artistSeriesConnection?.totalCount ?? 0) + excludedArtistSeriesCount + const totalCount = + Number(artist?.artistSeriesConnection?.totalCount ?? 0) + excludedArtistSeriesCount if (!artist || series.length === 0) { return null @@ -87,29 +88,32 @@ export const ArtistSeriesMoreSeries: React.FC = ({ ) } -export const ArtistSeriesMoreSeriesFragmentContainer = createFragmentContainer(ArtistSeriesMoreSeries, { - artist: graphql` - fragment ArtistSeriesMoreSeries_artist on Artist { - internalID - slug - artistSeriesConnection(first: 4) { - totalCount - edges { - node { - slug - internalID - title - featured - artworksCountMessage - image { - url +export const ArtistSeriesMoreSeriesFragmentContainer = createFragmentContainer( + ArtistSeriesMoreSeries, + { + artist: graphql` + fragment ArtistSeriesMoreSeries_artist on Artist { + internalID + slug + artistSeriesConnection(first: 4) { + totalCount + edges { + node { + slug + internalID + title + featured + artworksCountMessage + image { + url + } } } } } - } - `, -}) + `, + } +) export const tracks = { tapViewAllArtistSeries: (artistId: string, artistSlug: string) => ({ diff --git a/src/lib/Scenes/ArtistShows/ArtistShows2.tsx b/src/lib/Scenes/ArtistShows/ArtistShows2.tsx index b3d2f197dfb..1f1cccd2e1e 100644 --- a/src/lib/Scenes/ArtistShows/ArtistShows2.tsx +++ b/src/lib/Scenes/ArtistShows/ArtistShows2.tsx @@ -133,9 +133,15 @@ export const ArtistShows2PaginationContainer = createPaginationContainer( query: graphql` # Here is the query to fetch any specific page - query ArtistShows2PastShowsQuery($count: Int!, $cursor: String, $artistID: String!, $status: String!) { + query ArtistShows2PastShowsQuery( + $count: Int! + $cursor: String + $artistID: String! + $status: String! + ) { artist(id: $artistID) { - ...ArtistShows2_artist @arguments(count: $count, cursor: $cursor, artistID: $artistID, status: $status) + ...ArtistShows2_artist + @arguments(count: $count, cursor: $cursor, artistID: $artistID, status: $status) } } `, diff --git a/src/lib/Scenes/Artwork/Artwork.tests.tsx b/src/lib/Scenes/Artwork/Artwork.tests.tsx index 35ff9330712..77d41966fb0 100644 --- a/src/lib/Scenes/Artwork/Artwork.tests.tsx +++ b/src/lib/Scenes/Artwork/Artwork.tests.tsx @@ -360,7 +360,9 @@ describe("Artwork", () => { }) mockMostRecentOperation("ArtworkMarkAsRecentlyViewedQuery") - expect(tree.root.findByType(Artwork).props.artworkAboveTheFold.slug).toBe("completely-different-slug") + expect(tree.root.findByType(Artwork).props.artworkAboveTheFold.slug).toBe( + "completely-different-slug" + ) }) it("does not show a contextCard if the work is in a non-auction sale", async () => { @@ -406,7 +408,12 @@ describe("Artwork", () => { mockMostRecentOperation("ArtworkAboveTheFoldQuery", { Artwork() { - return merge({}, ArtworkFixture, ArtworkFromLiveAuctionRegistrationClosed, RegisteredBidder) + return merge( + {}, + ArtworkFixture, + ArtworkFromLiveAuctionRegistrationClosed, + RegisteredBidder + ) }, }) @@ -421,7 +428,12 @@ describe("Artwork", () => { mockMostRecentOperation("ArtworkAboveTheFoldQuery", { Artwork() { - return merge({}, ArtworkFixture, ArtworkFromLiveAuctionRegistrationClosed, NotRegisteredToBid) + return merge( + {}, + ArtworkFixture, + ArtworkFromLiveAuctionRegistrationClosed, + NotRegisteredToBid + ) }, }) @@ -437,7 +449,12 @@ describe("Artwork", () => { mockMostRecentOperation("ArtworkAboveTheFoldQuery", { Artwork() { - return merge({}, ArtworkFixture, ArtworkFromLiveAuctionRegistrationOpen, NotRegisteredToBid) + return merge( + {}, + ArtworkFixture, + ArtworkFromLiveAuctionRegistrationOpen, + NotRegisteredToBid + ) }, }) diff --git a/src/lib/Scenes/Artwork/Artwork.tsx b/src/lib/Scenes/Artwork/Artwork.tsx index c99f6b72e09..b728dd84118 100644 --- a/src/lib/Scenes/Artwork/Artwork.tsx +++ b/src/lib/Scenes/Artwork/Artwork.tsx @@ -40,7 +40,10 @@ import { ArtworksInSeriesRailFragmentContainer as ArtworksInSeriesRail } from ". import { CommercialInformationFragmentContainer as CommercialInformation } from "./Components/CommercialInformation" import { ContextCardFragmentContainer as ContextCard } from "./Components/ContextCard" import { getMeasurements } from "./Components/ImageCarousel/geometry" -import { OtherWorksFragmentContainer as OtherWorks, populatedGrids } from "./Components/OtherWorks/OtherWorks" +import { + OtherWorksFragmentContainer as OtherWorks, + populatedGrids, +} from "./Components/OtherWorks/OtherWorks" import { PartnerCardFragmentContainer as PartnerCard } from "./Components/PartnerCard" interface ArtworkProps { @@ -225,7 +228,9 @@ export const Artwork: React.FC = ({ sections.push({ key: "commercialInformation", - element: , + element: ( + + ), }) } @@ -251,7 +256,11 @@ export const Artwork: React.FC = ({ }) } - if (artworkBelowTheFold.provenance || artworkBelowTheFold.exhibitionHistory || artworkBelowTheFold.literature) { + if ( + artworkBelowTheFold.provenance || + artworkBelowTheFold.exhibitionHistory || + artworkBelowTheFold.literature + ) { sections.push({ key: "history", element: , @@ -348,7 +357,9 @@ export const Artwork: React.FC = ({ )} refreshControl={} contentContainerStyle={{ paddingBottom: 40 }} - renderItem={({ item }) => (item.excludePadding ? item.element : {item.element})} + renderItem={({ item }) => + item.excludePadding ? item.element : {item.element} + } /> )} @@ -598,7 +609,10 @@ const BelowTheFoldPlaceholder: React.FC<{}> = ({}) => { ) } -const getDefaultImageDimensions = (screenDimensions: ScreenDimensionsWithSafeAreas, space: number) => { +const getDefaultImageDimensions = ( + screenDimensions: ScreenDimensionsWithSafeAreas, + space: number +) => { // The logic for artworkHeight comes from the zeplin spec https://zpl.io/25JLX0Q return { width: (screenDimensions.width >= 375 ? 340 : 290) - space, diff --git a/src/lib/Scenes/Artwork/Components/AboutArtist.tsx b/src/lib/Scenes/Artwork/Components/AboutArtist.tsx index f3b3cb43a48..dd9ca5324aa 100644 --- a/src/lib/Scenes/Artwork/Components/AboutArtist.tsx +++ b/src/lib/Scenes/Artwork/Components/AboutArtist.tsx @@ -16,7 +16,8 @@ export const AboutArtist: React.FC = ({ artwork }) => { const hasSingleArtist = artists && artists.length === 1 - const text = hasSingleArtist && artists[0]?.biographyBlurb?.text ? artists[0]?.biographyBlurb?.text : null + const text = + hasSingleArtist && artists[0]?.biographyBlurb?.text ? artists[0]?.biographyBlurb?.text : null const textLimit = truncatedTextLimit() return ( @@ -29,7 +30,11 @@ export const AboutArtist: React.FC = ({ artwork }) => { {artists.map( (artist) => !!artist && ( - + ) )} diff --git a/src/lib/Scenes/Artwork/Components/ArtworkActions.tsx b/src/lib/Scenes/Artwork/Components/ArtworkActions.tsx index 394c4e67ba1..1bec865d2a7 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkActions.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkActions.tsx @@ -32,7 +32,11 @@ interface ArtworkActionsProps { shareOnPress: () => void } -export const shareContent = (title: string, href: string, artists: ArtworkActions_artwork["artists"]) => { +export const shareContent = ( + title: string, + href: string, + artists: ArtworkActions_artwork["artists"] +) => { let computedTitle: string | null if (artists && artists.length) { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -54,7 +58,9 @@ export const shareContent = (title: string, href: string, artists: ArtworkAction export class ArtworkActions extends React.Component { @track((props: ArtworkActionsProps) => { return { - action_name: props.artwork.is_saved ? Schema.ActionNames.ArtworkUnsave : Schema.ActionNames.ArtworkSave, + action_name: props.artwork.is_saved + ? Schema.ActionNames.ArtworkUnsave + : Schema.ActionNames.ArtworkSave, action_type: Schema.ActionTypes.Success, context_module: Schema.ContextModules.ArtworkActions, } @@ -75,7 +81,9 @@ export class ArtworkActions extends React.Component { `, variables: { input: { artworkID: artwork.internalID, remove: artwork.is_saved } }, // @ts-ignore RELAY 12 MIGRATION - optimisticResponse: { saveArtwork: { artwork: { id: artwork.id, is_saved: !artwork.is_saved } } }, + optimisticResponse: { + saveArtwork: { artwork: { id: artwork.id, is_saved: !artwork.is_saved } }, + }, onCompleted: () => userHadMeaningfulInteraction({ contextModule: ContextModule.artworkMetadata, @@ -98,7 +106,13 @@ export class ArtworkActions extends React.Component { const heightIn = cm2in(heightCm!) const widthIn = cm2in(widthCm!) - LegacyNativeModules.ARScreenPresenterModule.presentAugmentedRealityVIR(image?.url!, widthIn, heightIn, slug, id) + LegacyNativeModules.ARScreenPresenterModule.presentAugmentedRealityVIR( + image?.url!, + widthIn, + heightIn, + slug, + id + ) } render() { diff --git a/src/lib/Scenes/Artwork/Components/ArtworkDetailsRow.tsx b/src/lib/Scenes/Artwork/Components/ArtworkDetailsRow.tsx index 5106986d660..5748e2b4e8e 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkDetailsRow.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkDetailsRow.tsx @@ -18,7 +18,12 @@ interface ArtworkDetailsRowProps { } } -export const ArtworkDetailsRow: React.FC = ({ key, title, value, tracking }) => { +export const ArtworkDetailsRow: React.FC = ({ + key, + title, + value, + tracking, +}) => { return ( {title} diff --git a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tests.tsx b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tests.tsx index 013b487c1a5..9eee7baf4cb 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tests.tsx @@ -267,12 +267,18 @@ describe("ArtworkExtraLinks", () => { }) it("hides auction links when auctionState is closed", () => { - const componentWithEndedAuctionState = getWrapper({ artwork, auctionState: AuctionTimerState.CLOSED }) + const componentWithEndedAuctionState = getWrapper({ + artwork, + auctionState: AuctionTimerState.CLOSED, + }) expect(componentWithEndedAuctionState.text()).not.toContain("By placing a bid you agree to") }) it("displays auction links when auctionState is closing", () => { - const componentWithEndedAuctionState = getWrapper({ artwork, auctionState: AuctionTimerState.CLOSING }) + const componentWithEndedAuctionState = getWrapper({ + artwork, + auctionState: AuctionTimerState.CLOSING, + }) expect(componentWithEndedAuctionState.text()).toContain("By placing a bid you agree to") }) @@ -285,7 +291,10 @@ describe("ArtworkExtraLinks", () => { }) it("displays auction links when auctionState is inProgress", () => { - const componentWithEndedAuctionState = getWrapper({ artwork, auctionState: AuctionTimerState.CLOSING }) + const componentWithEndedAuctionState = getWrapper({ + artwork, + auctionState: AuctionTimerState.CLOSING, + }) expect(componentWithEndedAuctionState.text()).toContain("By placing a bid you agree to") }) diff --git a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tsx b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tsx index aa1072cce8b..41be4676472 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/index.tsx @@ -66,7 +66,10 @@ export class ArtworkExtraLinks extends React.Component { <> By placing a bid you agree to {partnerName(sale)}{" "} - this.handleConditionsOfSaleTap()}> + this.handleConditionsOfSaleTap()} + > Conditions of Sale . @@ -74,7 +77,10 @@ export class ArtworkExtraLinks extends React.Component { Have a question?{" "} - this.handleReadOurAuctionFAQsTap()}> + this.handleReadOurAuctionFAQsTap()} + > Read our auction FAQs {" "} or{" "} @@ -92,7 +98,10 @@ export class ArtworkExtraLinks extends React.Component { return ( Have a question?{" "} - this.handleReadOurFAQTap()}> + this.handleReadOurFAQTap()} + > Read our FAQ {" "} or{" "} @@ -123,7 +132,9 @@ export class ArtworkExtraLinks extends React.Component { <> {this.renderFAQAndSpecialist()} {!!consignableArtistsCount && ( - 1 ? "these artists" : artistName ?? "this artist"} /> + 1 ? "these artists" : artistName ?? "this artist"} + /> )} ) diff --git a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tests.tsx b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tests.tsx index 0e429a51352..144b0366187 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tests.tsx @@ -21,26 +21,36 @@ describe("partnerName", () => { it(`adds a "Artsy's" prefix and "s" to the end of the partner name if the partner name ends with "'" (normal single quote)`, () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(partnerName({ ...sale, partner: { name: "GALERIE K'" } })).toEqual("Artsy's and GALERIE K's") + expect(partnerName({ ...sale, partner: { name: "GALERIE K'" } })).toEqual( + "Artsy's and GALERIE K's" + ) }) it(`adds a "Artsy's" prefix and "s" to the end of the partner name if the partner name ends with "’" (smart quote)`, () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(partnerName({ ...sale, partner: { name: "GALERIE K’" } })).toEqual("Artsy's and GALERIE K’s") + expect(partnerName({ ...sale, partner: { name: "GALERIE K’" } })).toEqual( + "Artsy's and GALERIE K’s" + ) }) it(`only adds a "Artsy's" prefix if the partner name ends with a "'s" (normal single quote)`, () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(partnerName({ ...sale, partner: { name: "Christie's" } })).toEqual("Artsy's and Christie's") + expect(partnerName({ ...sale, partner: { name: "Christie's" } })).toEqual( + "Artsy's and Christie's" + ) }) it(`only adds a "Artsy's" prefix if the partner name ends with a "’s" (smart quote) `, () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(partnerName({ ...sale, partner: { name: "Christie’s" } })).toEqual("Artsy's and Christie’s") + expect(partnerName({ ...sale, partner: { name: "Christie’s" } })).toEqual( + "Artsy's and Christie’s" + ) }) it(`adds a "Artsy's" prefix and "'" (single quote) to the end of the partner name if the partner name ends with "s"`, () => { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(partnerName({ ...sale, partner: { name: "Phillips" } })).toEqual("Artsy's and Phillips's") + expect(partnerName({ ...sale, partner: { name: "Phillips" } })).toEqual( + "Artsy's and Phillips's" + ) }) }) diff --git a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tsx b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tsx index 9ea1896216e..3778139756b 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName.tsx @@ -2,7 +2,9 @@ import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwo import { ConfirmBid_sale_artwork } from "__generated__/ConfirmBid_sale_artwork.graphql" import { isEmpty } from "lodash" -type SaleWithPartner = NonNullable | NonNullable +type SaleWithPartner = + | NonNullable + | NonNullable export const partnerName = ({ isBenefit, partner }: SaleWithPartner) => { if (isBenefit || isEmpty(partner)) { diff --git a/src/lib/Scenes/Artwork/Components/ArtworkHeader.tsx b/src/lib/Scenes/Artwork/Components/ArtworkHeader.tsx index bd228bc2a2e..c2c4b61e09a 100644 --- a/src/lib/Scenes/Artwork/Components/ArtworkHeader.tsx +++ b/src/lib/Scenes/Artwork/Components/ArtworkHeader.tsx @@ -7,7 +7,16 @@ import { unsafe__getEnvironment, useDevToggle, useFeatureFlag } from "lib/store/ import { Schema } from "lib/utils/track" import { useCanOpenURL } from "lib/utils/useCanOpenURL" import { useScreenDimensions } from "lib/utils/useScreenDimensions" -import { Box, Flex, InstagramAppIcon, LinkIcon, MoreIcon, ShareIcon, Spacer, WhatsAppAppIcon } from "palette" +import { + Box, + Flex, + InstagramAppIcon, + LinkIcon, + MoreIcon, + ShareIcon, + Spacer, + WhatsAppAppIcon, +} from "palette" import React, { useRef, useState } from "react" import { Button, Modal } from "react-native" import { ScrollView } from "react-native-gesture-handler" @@ -90,7 +99,9 @@ export const ArtworkHeader: React.FC = (props) => { social: Share.Social.INSTAGRAM_STORIES, backgroundImage: base64Data, }) - trackEvent(share(tracks.customShare(CustomService.instagram_stories, artwork.internalID, artwork.slug))) + trackEvent( + share(tracks.customShare(CustomService.instagram_stories, artwork.internalID, artwork.slug)) + ) setShareSheetVisible(false) } @@ -111,7 +122,9 @@ export const ArtworkHeader: React.FC = (props) => { onImageIndexChange={(imageIndex) => setCurrentImageIndex(imageIndex)} /> - {debugInstagramShot ? {needsIdentityVerification && ( - this.redirectToIdentityVerificationFAQ()} /> + this.redirectToIdentityVerificationFAQ()} + /> )} )} @@ -117,7 +130,9 @@ export class BidButton extends React.Component { Registration pending {needsIdentityVerification && ( - this.redirectToIdentityVerificationFAQ()} /> + this.redirectToIdentityVerificationFAQ()} + /> )} )} @@ -163,8 +178,13 @@ export class BidButton extends React.Component { } const qualifiedForBidding = registrationStatus?.qualifiedForBidding - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const needsIdentityVerification = bidderNeedsIdentityVerification({ sale, user: me, bidder: registrationStatus }) + const needsIdentityVerification = bidderNeedsIdentityVerification({ + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + sale, + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + user: me, + bidder: registrationStatus, + }) /** * NOTE: This is making an incorrect assumption that there could only ever @@ -185,7 +205,9 @@ export class BidButton extends React.Component { Registration pending {needsIdentityVerification && ( - this.redirectToIdentityVerificationFAQ()} /> + this.redirectToIdentityVerificationFAQ()} + /> )} ) @@ -202,19 +224,30 @@ export class BidButton extends React.Component { - this.redirectToIdentityVerificationFAQ()} /> + this.redirectToIdentityVerificationFAQ()} + /> ) } else { const myLastMaxBid = hasBid && myLotStanding.mostRecentBid.maxBid.cents // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const increments = saleArtwork.increments.filter((increment) => increment.cents > (myLastMaxBid || 0)) + const increments = saleArtwork.increments.filter( + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + (increment) => increment.cents > (myLastMaxBid || 0) + ) const firstIncrement = increments && increments.length && increments[0] const incrementCents = firstIncrement && firstIncrement.cents return ( - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - ) diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/BuyNowButton.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/BuyNowButton.tsx index 3a7946fd4e1..9c060826946 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/BuyNowButton.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/BuyNowButton.tsx @@ -31,18 +31,22 @@ export class BuyNowButton extends React.Component { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 onMutationError(error) { - Alert.alert("Sorry, we couldn't process the request.", "Please try again or contact orders@artsy.net for help.", [ - { - text: "Cancel", - style: "cancel", - }, - { - text: "Retry", - onPress: () => { - this.handleCreateOrder() + Alert.alert( + "Sorry, we couldn't process the request.", + "Please try again or contact orders@artsy.net for help.", + [ + { + text: "Cancel", + style: "cancel", }, - }, - ]) + { + text: "Retry", + onPress: () => { + this.handleCreateOrder() + }, + }, + ] + ) console.log("src/lib/Scenes/Artwork/Components/BuyNowButton.tsx", error) } @@ -101,12 +105,17 @@ export class BuyNowButton extends React.Component { if (orderOrError.__typename === "CommerceOrderWithMutationFailure") { this.onMutationError(orderOrError.error) } else if (orderOrError.__typename === "CommerceOrderWithMutationSuccess") { - navigate(`/orders/${orderOrError.order.internalID}`, { modal: true, passProps: { title: "Buy Now" } }) + navigate(`/orders/${orderOrError.order.internalID}`, { + modal: true, + passProps: { title: "Buy Now" }, + }) } }) }, onError: (error) => - this.setState({ isCommittingCreateOrderMutation: false }, () => this.onMutationError(error)), + this.setState({ isCommittingCreateOrderMutation: false }, () => + this.onMutationError(error) + ), }) } }) @@ -126,7 +135,9 @@ export class BuyNowButton extends React.Component { width={100} haptic > - {variant && variant === "outline" && artwork.saleMessage ? `Buy now ${artwork.saleMessage}` : "Buy now"} + {variant && variant === "outline" && artwork.saleMessage + ? `Buy now ${artwork.saleMessage}` + : "Buy now"} ) } diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/CollapsibleArtworkDetails.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/CollapsibleArtworkDetails.tsx index 6eed54082e3..e0056cb3874 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/CollapsibleArtworkDetails.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/CollapsibleArtworkDetails.tsx @@ -21,7 +21,10 @@ const artworkDetailItems = (artwork: CollapsibleArtworkDetails_artwork) => { { title: "Publisher", value: artwork.publisher }, { title: "Materials", value: artwork.medium }, { title: "Classification", value: artwork.attributionClass?.name }, - { title: "Dimensions", value: [artwork.dimensions?.in, artwork.dimensions?.cm].filter((d) => d).join("\n") }, + { + title: "Dimensions", + value: [artwork.dimensions?.in, artwork.dimensions?.cm].filter((d) => d).join("\n"), + }, { title: "Signature", value: artwork.signatureInfo?.details }, { title: "Frame", value: artwork.framed?.details }, { title: "Certificate of Authenticity", value: artwork.certificateOfAuthenticity?.details }, @@ -86,42 +89,45 @@ export const CollapsibleArtworkDetails: React.FC ) : null } -export const CollapsibleArtworkDetailsFragmentContainer = createFragmentContainer(CollapsibleArtworkDetails, { - artwork: graphql` - fragment CollapsibleArtworkDetails_artwork on Artwork { - image { - url - width - height +export const CollapsibleArtworkDetailsFragmentContainer = createFragmentContainer( + CollapsibleArtworkDetails, + { + artwork: graphql` + fragment CollapsibleArtworkDetails_artwork on Artwork { + image { + url + width + height + } + internalID + title + date + saleMessage + attributionClass { + name + } + category + manufacturer + publisher + medium + conditionDescription { + details + } + certificateOfAuthenticity { + details + } + framed { + details + } + dimensions { + in + cm + } + signatureInfo { + details + } + artistNames } - internalID - title - date - saleMessage - attributionClass { - name - } - category - manufacturer - publisher - medium - conditionDescription { - details - } - certificateOfAuthenticity { - details - } - framed { - details - } - dimensions { - in - cm - } - signatureInfo { - details - } - artistNames - } - `, -}) + `, + } +) diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tests.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tests.tsx index 61a522a66fd..8db57e9869f 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tests.tsx @@ -14,8 +14,14 @@ import { CommercialButtonsFragmentContainer } from "./CommercialButtons" jest.unmock("react-relay") -// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 -const componentWithQuery = async ({ mockArtworkData, mockOrderMutationResults, mockOfferMutationResults }) => { +const componentWithQuery = async ({ + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + mockArtworkData, + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + mockOrderMutationResults, + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + mockOfferMutationResults, +}) => { return await renderRelayTree({ Component: CommercialButtonsFragmentContainer, query: graphql` @@ -196,7 +202,10 @@ describe("CommercialButtons", () => { const BuyNowButton = commercialButtons.find(Button).at(0) BuyNowButton.props().onPress() await flushPromiseQueue() - expect(navigate).toHaveBeenCalledWith("/orders/buyNowID", { modal: true, passProps: { title: "Buy Now" } }) + expect(navigate).toHaveBeenCalledWith("/orders/buyNowID", { + modal: true, + passProps: { title: "Buy Now" }, + }) }) it("commits the Make Offer mutation", async () => { diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tsx index ccab6899d9b..9fba69f25af 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/CommercialButtons.tsx @@ -36,7 +36,15 @@ export class CommercialButtons extends React.Component { render() { const { artwork, me, auctionState } = this.props - const { isBuyNowable, isAcquireable, isOfferable, isInquireable, isInAuction, editionSets, isForSale } = artwork + const { + isBuyNowable, + isAcquireable, + isOfferable, + isInquireable, + isInAuction, + editionSets, + isForSale, + } = artwork const noEditions = (editionSets && editionSets.length === 0) || !editionSets // GOTCHA: Don't copy this kind of feature flag code if you're working in a functional component. use `useFeatureFlag` instead const newFirstInquiry = unsafe_getFeatureFlag("AROptionsNewFirstInquiry") @@ -78,11 +86,18 @@ export class CommercialButtons extends React.Component { ) } else if (isAcquireable) { - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - return + return ( + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + + ) } else if (isOfferable) { - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - return + return ( + + ) } else if (isInquireable && !newFirstInquiry) { return ( ) } else if (isInquireable && newFirstInquiry) { - return + return ( + + ) } else { return <> } diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tests.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tests.tsx index a227a997d16..e79b4dfa7f1 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tests.tsx @@ -59,7 +59,9 @@ const TestRenderer = () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tsx index 9db5d52eb80..c119e7358f5 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryButtons.tsx @@ -1,7 +1,10 @@ import { ActionType, OwnerType, TappedContactGallery } from "@artsy/cohesion" import { InquiryButtons_artwork } from "__generated__/InquiryButtons_artwork.graphql" import { InquirySuccessNotification } from "lib/Scenes/Artwork/Components/CommercialButtons/InquirySuccessNotification" -import { ArtworkInquiryContext, ArtworkInquiryStateProvider } from "lib/utils/ArtworkInquiry/ArtworkInquiryStore" +import { + ArtworkInquiryContext, + ArtworkInquiryStateProvider, +} from "lib/utils/ArtworkInquiry/ArtworkInquiryStore" import { InquiryTypes } from "lib/utils/ArtworkInquiry/ArtworkInquiryTypes" import { InquiryOptions } from "lib/utils/ArtworkInquiry/ArtworkInquiryTypes" import { Button, ButtonProps } from "palette" diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tests.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tests.tsx index 78e1a92901b..4bcc4e82e7f 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tests.tsx @@ -3,12 +3,18 @@ jest.mock("lib/utils/googleMaps", () => ({ getLocationDetails: jest.fn(), })) -import { InquiryModalTestsQuery, InquiryModalTestsQueryResponse } from "__generated__/InquiryModalTestsQuery.graphql" +import { + InquiryModalTestsQuery, + InquiryModalTestsQueryResponse, +} from "__generated__/InquiryModalTestsQuery.graphql" import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader" import { extractText } from "lib/tests/extractText" import { flushPromiseQueue } from "lib/tests/flushPromiseQueue" import { renderWithWrappers } from "lib/tests/renderWithWrappers" -import { ArtworkInquiryContext, ArtworkInquiryStateProvider } from "lib/utils/ArtworkInquiry/ArtworkInquiryStore" +import { + ArtworkInquiryContext, + ArtworkInquiryStateProvider, +} from "lib/utils/ArtworkInquiry/ArtworkInquiryStore" import React from "react" import { TextInput } from "react-native" import { graphql, QueryRenderer } from "react-relay" diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tsx index 57b9fe5281d..23c7de19be3 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquiryModal.tsx @@ -89,7 +89,11 @@ const InquiryQuestionOption: React.FC<{ }> - + {question} diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquirySuccessNotification.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquirySuccessNotification.tsx index 1aafc579ea3..5a967ca0417 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/InquirySuccessNotification.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/InquirySuccessNotification.tsx @@ -33,7 +33,12 @@ export const InquirySuccessNotification: React.FC toggleNotification(false)} animationType="fade" transparent> + toggleNotification(false)} + animationType="fade" + transparent + > - renderWithWrappers() + renderWithWrappers( + + ) const locationQueryResult = [ { id: "a", name: "Busytown, USA" }, diff --git a/src/lib/Scenes/Artwork/Components/CommercialButtons/MakeOfferButton.tsx b/src/lib/Scenes/Artwork/Components/CommercialButtons/MakeOfferButton.tsx index 874583fdc9b..183022630dc 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialButtons/MakeOfferButton.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialButtons/MakeOfferButton.tsx @@ -37,18 +37,22 @@ export class MakeOfferButton extends React.Component { - this.handleCreateOfferOrder() + Alert.alert( + "Sorry, we couldn't process the request.", + "Please try again or contact orders@artsy.net for help.", + [ + { + text: "Cancel", + style: "cancel", }, - }, - ]) + { + text: "Retry", + onPress: () => { + this.handleCreateOfferOrder() + }, + }, + ] + ) console.log("src/lib/Scenes/Artwork/Components/MakeOfferButton.tsx", error) } @@ -72,7 +76,9 @@ export class MakeOfferButton extends React.Component(relay.environment, { mutation: graphql` - mutation MakeOfferButtonOrderMutation($input: CommerceCreateOfferOrderWithArtworkInput!) { + mutation MakeOfferButtonOrderMutation( + $input: CommerceCreateOfferOrderWithArtworkInput! + ) { commerceCreateOfferOrderWithArtwork(input: $input) { orderOrError { __typename @@ -116,7 +122,9 @@ export class MakeOfferButton extends React.Component - this.setState({ isCommittingCreateOfferOrderMutation: false }, () => this.onMutationError(error)), + this.setState({ isCommittingCreateOfferOrderMutation: false }, () => + this.onMutationError(error) + ), }) } }) diff --git a/src/lib/Scenes/Artwork/Components/CommercialInformation.tests.tsx b/src/lib/Scenes/Artwork/Components/CommercialInformation.tests.tsx index 623f9f7363b..0e1693d6683 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialInformation.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialInformation.tests.tsx @@ -34,7 +34,10 @@ describe("CommercialInformation", () => { const component = mount( - + ) @@ -52,12 +55,17 @@ describe("CommercialInformation", () => { const component = mount( - + ) expect(component.text()).toContain("On hold") - expect(component.find(SaleAvailability).first().prop("dotColor")).toEqual(_test_THEMES.v2.colors.yellow100) // we dont have a v3 yellow yet, so we are keeping the v2 for now. + expect(component.find(SaleAvailability).first().prop("dotColor")).toEqual( + _test_THEMES.v2.colors.yellow100 + ) // we dont have a v3 yellow yet, so we are keeping the v2 for now. }) it("renders red indicator and correct message when artwork is sold", () => { @@ -69,12 +77,17 @@ describe("CommercialInformation", () => { const component = mount( - + ) expect(component.text()).toContain("Sold") - expect(component.find(SaleAvailability).first().prop("dotColor")).toEqual(_test_THEMES.v3.colors.red100) + expect(component.find(SaleAvailability).first().prop("dotColor")).toEqual( + _test_THEMES.v3.colors.red100 + ) }) it("renders green indicator and correct message when artwork is for sale", () => { @@ -86,12 +99,17 @@ describe("CommercialInformation", () => { const component = mount( - + ) expect(component.text()).toContain("For sale") - expect(component.find(SaleAvailability).first().prop("dotColor")).toEqual(_test_THEMES.v3.colors.green100) + expect(component.find(SaleAvailability).first().prop("dotColor")).toEqual( + _test_THEMES.v3.colors.green100 + ) }) it("renders Bidding Closed and no CommercialButtons for auction works when the auction has ended", () => { @@ -269,13 +287,20 @@ describe("CommercialInformation", () => { ) // Expect the component to default to first edition set's internalID - expect(component.find(CommercialButtons).props().editionSetID).toEqual("5bbb9777ce2fc3002c179013") + expect(component.find(CommercialButtons).props().editionSetID).toEqual( + "5bbb9777ce2fc3002c179013" + ) - const secondEditionButton = component.find(CommercialEditionSetInformation).find(TouchableWithoutFeedback).at(2) + const secondEditionButton = component + .find(CommercialEditionSetInformation) + .find(TouchableWithoutFeedback) + .at(2) secondEditionButton.props().onPress() component.update() - expect(component.find(CommercialButtons).props().editionSetID).toEqual("5bc0ec007e64300a39b23da4") + expect(component.find(CommercialButtons).props().editionSetID).toEqual( + "5bc0ec007e64300a39b23da4" + ) }) }) @@ -400,7 +425,10 @@ describe("ArtworkExtraLinks", () => { const component = mount( - + ) expect(component.find(ArtworkExtraLinks).length).toEqual(1) diff --git a/src/lib/Scenes/Artwork/Components/CommercialInformation.tsx b/src/lib/Scenes/Artwork/Components/CommercialInformation.tsx index 72fc9b18021..8deb9c2b04f 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialInformation.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialInformation.tsx @@ -60,7 +60,9 @@ export const CommercialInformationTimerWrapper: React.FC { - const nextState = nextTimerState(state as AuctionTimerState, { liveStartsAt: liveStartsAt || undefined }) + const nextState = nextTimerState(state as AuctionTimerState, { + liveStartsAt: liveStartsAt || undefined, + }) const { label, date } = relevantStateData(nextState, { liveStartsAt: liveStartsAt || undefined, startsAt: startsAt || undefined, @@ -86,7 +88,10 @@ const ColoredDot = styled(Box)<{ dotColor: string }>` margin-right: 8px; ` -export const SaleAvailability: React.FC<{ dotColor?: string; saleMessage: string }> = ({ dotColor, saleMessage }) => { +export const SaleAvailability: React.FC<{ dotColor?: string; saleMessage: string }> = ({ + dotColor, + saleMessage, +}) => { return ( @@ -126,7 +131,9 @@ export const CommercialInformation: React.FC = ({ const renderSingleEditionArtwork = () => { const artworkIsInClosedAuction = artwork.isInAuction && timerState === AuctionTimerState.CLOSED - const saleMessage = artwork.saleMessage ? artwork.saleMessage : capitalize(artwork.availability || undefined) + const saleMessage = artwork.saleMessage + ? artwork.saleMessage + : capitalize(artwork.availability || undefined) return ( @@ -134,7 +141,10 @@ export const CommercialInformation: React.FC = ({ let indicatorColor let newSaleMessage - if (artwork.availability?.toLowerCase() === "on loan" || artwork.availability?.toLowerCase() === "on hold") { + if ( + artwork.availability?.toLowerCase() === "on loan" || + artwork.availability?.toLowerCase() === "on hold" + ) { indicatorColor = color("yellow100") } else if ( artwork.availability?.toLowerCase() === "sold" || @@ -143,14 +153,20 @@ export const CommercialInformation: React.FC = ({ indicatorColor = color("red100") } else if (artworkIsInClosedAuction) { newSaleMessage = "Bidding closed" - } else if (artwork.saleMessage?.toLowerCase() === "contact for price" && artwork.isForSale) { + } else if ( + artwork.saleMessage?.toLowerCase() === "contact for price" && + artwork.isForSale + ) { newSaleMessage = "For sale" indicatorColor = color("green100") } return ( <> - + {!artworkIsInClosedAuction && } ) @@ -186,11 +202,14 @@ export const CommercialInformation: React.FC = ({ const { isAcquireable, isOfferable, isInquireable, isInAuction, sale, isForSale } = artwork - const isBiddableInAuction = isInAuction && sale && timerState !== AuctionTimerState.CLOSED && isForSale + const isBiddableInAuction = + isInAuction && sale && timerState !== AuctionTimerState.CLOSED && isForSale const isInClosedAuction = isInAuction && sale && timerState === AuctionTimerState.CLOSED - const canTakeCommercialAction = isAcquireable || isOfferable || isInquireable || isBiddableInAuction + const canTakeCommercialAction = + isAcquireable || isOfferable || isInquireable || isBiddableInAuction const artistIsConsignable = artwork?.artists?.filter((artist) => artist?.isConsignable).length - const hidesPriceInformation = isInAuction && isForSale && timerState === AuctionTimerState.LIVE_INTEGRATION_ONGOING + const hidesPriceInformation = + isInAuction && isForSale && timerState === AuctionTimerState.LIVE_INTEGRATION_ONGOING return ( <> @@ -234,49 +253,52 @@ export const CommercialInformation: React.FC = ({ ) } -export const CommercialInformationFragmentContainer = createFragmentContainer(CommercialInformationTimerWrapper, { - artwork: graphql` - fragment CommercialInformation_artwork on Artwork { - isAcquireable - isOfferable - isInquireable - isInAuction - availability - saleMessage - isForSale - internalID - slug +export const CommercialInformationFragmentContainer = createFragmentContainer( + CommercialInformationTimerWrapper, + { + artwork: graphql` + fragment CommercialInformation_artwork on Artwork { + isAcquireable + isOfferable + isInquireable + isInAuction + availability + saleMessage + isForSale + internalID + slug - artists { - isConsignable - } + artists { + isConsignable + } - editionSets { - id - } + editionSets { + id + } - sale { - internalID - isClosed - isAuction - isLiveOpen - isPreview - liveStartAt - endAt - slug - startAt - } + sale { + internalID + isClosed + isAuction + isLiveOpen + isPreview + liveStartAt + endAt + slug + startAt + } - ...CommercialButtons_artwork - ...CommercialPartnerInformation_artwork - ...CommercialEditionSetInformation_artwork - ...ArtworkExtraLinks_artwork - ...AuctionPrice_artwork - } - `, - me: graphql` - fragment CommercialInformation_me on Me { - ...CommercialButtons_me - } - `, -}) + ...CommercialButtons_artwork + ...CommercialPartnerInformation_artwork + ...CommercialEditionSetInformation_artwork + ...ArtworkExtraLinks_artwork + ...AuctionPrice_artwork + } + `, + me: graphql` + fragment CommercialInformation_me on Me { + ...CommercialButtons_me + } + `, + } +) diff --git a/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tests.tsx b/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tests.tsx index afecc61a6d9..9b5770a0666 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tests.tsx @@ -18,9 +18,15 @@ describe("CommercialPartnerInformation", () => { ) expect(component.find(Sans).at(0).render().text()).toMatchInlineSnapshot(`"From Bob's Gallery"`) - expect(component.find(Sans).at(1).render().text()).toMatchInlineSnapshot(`"Ships from Brooklyn"`) - expect(component.find(Sans).at(2).render().text()).toMatchInlineSnapshot(`"Ships within the continental USA"`) - expect(component.find(Sans).at(3).render().text()).toMatchInlineSnapshot(`"VAT included in price"`) + expect(component.find(Sans).at(1).render().text()).toMatchInlineSnapshot( + `"Ships from Brooklyn"` + ) + expect(component.find(Sans).at(2).render().text()).toMatchInlineSnapshot( + `"Ships within the continental USA"` + ) + expect(component.find(Sans).at(3).render().text()).toMatchInlineSnapshot( + `"VAT included in price"` + ) }) it("hides shipping info for works from closed auctions", () => { diff --git a/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tsx b/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tsx index 061f27fb81d..8dcae8578de 100644 --- a/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tsx +++ b/src/lib/Scenes/Artwork/Components/CommercialPartnerInformation.tsx @@ -44,19 +44,22 @@ export class CommercialPartnerInformation extends React.Component { } } -export const CommercialPartnerInformationFragmentContainer = createFragmentContainer(CommercialPartnerInformation, { - artwork: graphql` - fragment CommercialPartnerInformation_artwork on Artwork { - availability - isAcquireable - isForSale - isOfferable - shippingOrigin - shippingInfo - priceIncludesTaxDisplay - partner { - name +export const CommercialPartnerInformationFragmentContainer = createFragmentContainer( + CommercialPartnerInformation, + { + artwork: graphql` + fragment CommercialPartnerInformation_artwork on Artwork { + availability + isAcquireable + isForSale + isOfferable + shippingOrigin + shippingInfo + priceIncludesTaxDisplay + partner { + name + } } - } - `, -}) + `, + } +) diff --git a/src/lib/Scenes/Artwork/Components/ContextCard.tests.tsx b/src/lib/Scenes/Artwork/Components/ContextCard.tests.tsx index 221b5d88234..de359050251 100644 --- a/src/lib/Scenes/Artwork/Components/ContextCard.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/ContextCard.tests.tsx @@ -15,7 +15,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -28,7 +31,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -42,7 +48,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -55,7 +64,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -67,13 +79,18 @@ describe("ContextCard", () => { const component = mount( - + ) expect(component.find(Button)).toHaveLength(1) - expect(component.find(Button).at(0).render().text()).toMatchInlineSnapshot(`"FollowingFollow"`) + expect(component.find(Button).at(0).render().text()).toMatchInlineSnapshot( + `"FollowingFollow"` + ) }) }) @@ -82,7 +99,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -95,7 +115,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -115,7 +138,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -128,7 +154,10 @@ describe("ContextCard", () => { const component = mount( - + ) @@ -140,7 +169,10 @@ describe("ContextCard", () => { const component = mount( - + ) diff --git a/src/lib/Scenes/Artwork/Components/ContextCard.tsx b/src/lib/Scenes/Artwork/Components/ContextCard.tsx index eb47fdf1bf1..ab951875395 100644 --- a/src/lib/Scenes/Artwork/Components/ContextCard.tsx +++ b/src/lib/Scenes/Artwork/Components/ContextCard.tsx @@ -104,7 +104,9 @@ export class ContextCard extends React.Component { const { isFollowed } = show - return this.handleFollowShow(show)} /> + return ( + this.handleFollowShow(show)} /> + ) } render() { diff --git a/src/lib/Scenes/Artwork/Components/FollowArtistLink.tests.tsx b/src/lib/Scenes/Artwork/Components/FollowArtistLink.tests.tsx index c35f19455fb..4cf85c6469e 100644 --- a/src/lib/Scenes/Artwork/Components/FollowArtistLink.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/FollowArtistLink.tests.tsx @@ -28,7 +28,9 @@ describe("FollowArtistLink", () => { ) expect(component.find(TouchableWithoutFeedback).length).toEqual(1) - expect(component.find(TouchableWithoutFeedback).at(0).render().text()).toMatchInlineSnapshot(`"Follow"`) + expect(component.find(TouchableWithoutFeedback).at(0).render().text()).toMatchInlineSnapshot( + `"Follow"` + ) }) describe("Following an artist", () => { diff --git a/src/lib/Scenes/Artwork/Components/FollowArtistLink.tsx b/src/lib/Scenes/Artwork/Components/FollowArtistLink.tsx index ecb04801947..8e45058da86 100644 --- a/src/lib/Scenes/Artwork/Components/FollowArtistLink.tsx +++ b/src/lib/Scenes/Artwork/Components/FollowArtistLink.tsx @@ -15,7 +15,9 @@ interface Props { export class FollowArtistLink extends React.Component { @track((props: Props) => { return { - action_name: props.artist.is_followed ? Schema.ActionNames.ArtistUnfollow : Schema.ActionNames.ArtistFollow, + action_name: props.artist.is_followed + ? Schema.ActionNames.ArtistUnfollow + : Schema.ActionNames.ArtistFollow, action_type: Schema.ActionTypes.Success, owner_id: props.artist.internalID, owner_slug: props.artist.slug, diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomLevel.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomLevel.tsx index fc0c8903a2c..96e06bc6f3e 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomLevel.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomLevel.tsx @@ -58,8 +58,12 @@ export const DeepZoomLevel: React.FC<{ const transform = useMemo(() => { // in debug mode we ignore the controlling ScrollView so that it doesn't zoom or pan and you can see the whole pyramid at a glance const zoomScale = VISUAL_DEBUG_MODE ? 1 : $zoomScale - const contentOffsetY = VISUAL_DEBUG_MODE ? -imageFittedWithinScreen.marginVertical : $contentOffsetY - const contentOffsetX = VISUAL_DEBUG_MODE ? -imageFittedWithinScreen.marginHorizontal : $contentOffsetX + const contentOffsetY = VISUAL_DEBUG_MODE + ? -imageFittedWithinScreen.marginVertical + : $contentOffsetY + const contentOffsetX = VISUAL_DEBUG_MODE + ? -imageFittedWithinScreen.marginHorizontal + : $contentOffsetX // the first thing we want to do is place this level directly over the place where the base // image in the scroll view is (so, centered on screen when zoomScale === 1) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomOverlay.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomOverlay.tsx index 82bf217622f..735ec70343a 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomOverlay.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomOverlay.tsx @@ -4,7 +4,11 @@ import { Animated, View } from "react-native" import { fitInside, Rect } from "../../geometry" import { ImageDescriptor } from "../../ImageCarouselContext" import { EventStream } from "../useEventStream" -import { calculateDeepZoomLevels, calculateMinMaxDeepZoomLevels, getZoomScaleBoundaries } from "./deepZoomGeometry" +import { + calculateDeepZoomLevels, + calculateMinMaxDeepZoomLevels, + getZoomScaleBoundaries, +} from "./deepZoomGeometry" import { DeepZoomLevel } from "./DeepZoomLevel" import { DeepZoomPyramid } from "./DeepZoomPyramid" @@ -51,7 +55,10 @@ export const DeepZoomOverlay: React.FC = ({ // setup geometry const levels = useMemo(() => calculateDeepZoomLevels(fullImageSize), [fullImageSize]) - const imageFittedWithinScreen = useMemo(() => fitInside(screenDimensions, { width, height }), [width, height]) + const imageFittedWithinScreen = useMemo( + () => fitInside(screenDimensions, { width, height }), + [width, height] + ) const zoomScaleBoundaries = useMemo( () => getZoomScaleBoundaries({ imageFittedWithinScreen, levels }), [levels, imageFittedWithinScreen] diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomTile.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomTile.tsx index bd60305868b..02085210293 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomTile.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/DeepZoomTile.tsx @@ -12,7 +12,11 @@ export class DeepZoomTileID { return new DeepZoomTileID(level, row, col).intern() } id: string | null = null - private constructor(public readonly level: number, public readonly row: number, public readonly col: number) {} + private constructor( + public readonly level: number, + public readonly row: number, + public readonly col: number + ) {} toString() { if (this.id !== null) { return this.id @@ -45,7 +49,15 @@ export interface DeepZoomTileProps { /** * A tile is a single image in the pyramid */ -export const DeepZoomTile: React.FC = ({ url, top, left, width, height, id, pyramid }) => { +export const DeepZoomTile: React.FC = ({ + url, + top, + left, + width, + height, + id, + pyramid, +}) => { const [showing, setShowing] = useState(false) const [loaded, setLoaded] = useState(false) const isMounted = useIsMounted() diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/deepZoomGeometry.ts b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/deepZoomGeometry.ts index 1a15ea05870..ad9cf4b7ffa 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/deepZoomGeometry.ts +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/DeepZoom/deepZoomGeometry.ts @@ -26,7 +26,10 @@ export const calculateDeepZoomLevels = ({ width, height }: DeepZoomImageSize) => /** * calculates the max ScrollView.zoomScale for this image */ -export const calculateMaxZoomViewScale = (imageFittedWithinScreen: Size, fullResolutionImage: DeepZoomImageSize) => { +export const calculateMaxZoomViewScale = ( + imageFittedWithinScreen: Size, + fullResolutionImage: DeepZoomImageSize +) => { return fullResolutionImage.height / imageFittedWithinScreen.height } @@ -35,7 +38,10 @@ export const calculateMaxZoomViewScale = (imageFittedWithinScreen: Size, fullRes * is around level 9. This function figures it out! I have a feeling this could be done with logarithms rather than a * for loop, but I forgot all the maths I ever learned about 5 years ago. */ -export const calculateMinMaxDeepZoomLevels = (imageFittedWithinScreen: Size, zoomLevels: Size[]) => { +export const calculateMinMaxDeepZoomLevels = ( + imageFittedWithinScreen: Size, + zoomLevels: Size[] +) => { let minLevel = 0 const maxLevel = zoomLevels.length - 1 for (const { width } of zoomLevels) { diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselCloseButton.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselCloseButton.tsx index a8df114f348..2c4463dcdd0 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselCloseButton.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselCloseButton.tsx @@ -14,7 +14,8 @@ export const ImageCarouselCloseButton = ({ onClose }: { onClose(): void }) => { fullScreenState.useUpdates() const showCloseButton = - fullScreenState.current === "entered" || fullScreenState.current === "animating entry transition" + fullScreenState.current === "entered" || + fullScreenState.current === "animating entry transition" return ( { const Mock = () => { const value = useNewImageCarouselContext({ images: [ - { height: 5, width: 5, url: "a", deepZoom: { image: { size: { width: 5, height: 5 } } as any } }, - { height: 5, width: 5, url: "b", deepZoom: { image: { size: { width: 5, height: 5 } } as any } }, + { + height: 5, + width: 5, + url: "a", + deepZoom: { image: { size: { width: 5, height: 5 } } as any }, + }, + { + height: 5, + width: 5, + url: "b", + deepZoom: { image: { size: { width: 5, height: 5 } } as any }, + }, ], }) return ( diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselFullScreen.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselFullScreen.tsx index 5a5787a3a69..c363a06a11a 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselFullScreen.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/ImageCarouselFullScreen.tsx @@ -1,6 +1,13 @@ import { useScreenDimensions } from "lib/utils/useScreenDimensions" import React, { useCallback, useContext, useEffect, useMemo, useState } from "react" -import { Animated, Easing, FlatList, Modal, NativeScrollEvent, NativeSyntheticEvent } from "react-native" +import { + Animated, + Easing, + FlatList, + Modal, + NativeScrollEvent, + NativeSyntheticEvent, +} from "react-native" import { ImageCarouselContext, ImageDescriptor } from "../ImageCarouselContext" import { useAnimatedValue } from "../useAnimatedValue" import { ImageCarouselCloseButton } from "./ImageCarouselCloseButton" @@ -56,7 +63,12 @@ export const ImageCarouselFullScreen = () => { return ( // on mount we want the modal to be visible instantly and handle transitions elsewhere ourselves // on unmount we use it's built-in fade transition - + => - new Promise((resolve) => ref.measure((_, __, width, height, x, y) => resolve({ x, y, width, height }))) + new Promise((resolve) => + ref.measure((_, __, width, height, x, y) => resolve({ x, y, width, height })) + ) interface TransitionOffset { translateX: number @@ -49,7 +59,13 @@ interface TransitionOffset { // calculates the transition offset between the embedded thumbnail (fromRef) // and the full-screen image position (toBox) -async function getTransitionOffset({ fromRef, toBox }: { fromRef: View; toBox: Rect }): Promise { +async function getTransitionOffset({ + fromRef, + toBox, +}: { + fromRef: View + toBox: Rect +}): Promise { const fromBox = await measure(fromRef) const scale = fromBox.width / toBox.width @@ -116,7 +132,10 @@ export const ImageZoomView = }) const transition = useAnimatedValue(0) - const transform = useMemo(() => createTransform(transition, imageTransitionOffset), [imageTransitionOffset]) + const transform = useMemo( + () => createTransform(transition, imageTransitionOffset), + [imageTransitionOffset] + ) const rawImageSize = image?.deepZoom?.image?.size if (!rawImageSize) { @@ -296,7 +315,14 @@ export const ImageZoomView = ref={scrollViewRef} scrollEnabled={fullScreenState.current === "entered"} onScroll={Animated.event( - [{ nativeEvent: { zoomScale: $zoomScale, contentOffset: { x: $contentOffsetX, y: $contentOffsetY } } }], + [ + { + nativeEvent: { + zoomScale: $zoomScale, + contentOffset: { x: $contentOffsetX, y: $contentOffsetY }, + }, + }, + ], { useNativeDriver: true, listener: onScroll, diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/VerticalSwipeToDismiss.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/VerticalSwipeToDismiss.tsx index 866a51557a7..3f361898ec1 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/VerticalSwipeToDismiss.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/VerticalSwipeToDismiss.tsx @@ -105,7 +105,9 @@ export const VerticalSwipeToDismiss: React.FC<{ onClose(): void }> = ({ children scrollEventThrottle={0.000000001} > - {children} + + {children} + ) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/useSpringFade.ts b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/useSpringFade.ts index b73d1ba3ef2..7a184d22f0b 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/useSpringFade.ts +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/FullScreen/useSpringFade.ts @@ -11,7 +11,8 @@ export const useSpringFade = (fade: "in" | "out") => { const { fullScreenState } = useContext(ImageCarouselContext) fullScreenState.useUpdates() const isFullScreenReady = - fullScreenState.current === "animating entry transition" || fullScreenState.current === "entered" + fullScreenState.current === "animating entry transition" || + fullScreenState.current === "entered" const [from, to] = fade === "in" ? [0, 1] : [1, 0] return useSpringValue(isFullScreenReady ? to : from) } diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tests.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tests.tsx index 382b0545dca..e127138ccdc 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tests.tsx @@ -17,7 +17,9 @@ import { ImageWithLoadingState } from "./ImageWithLoadingState" jest.unmock("react-relay") const deepZoomFixture: NonNullable< - NonNullable["images"]>[0]>["deepZoom"] + NonNullable< + NonNullable["images"]>[0] + >["deepZoom"] > = { image: { format: "jpg", @@ -95,7 +97,9 @@ const localImages: CarouselImageDescriptor[] = [ describe("ImageCarouselFragmentContainer", () => { const getWrapper = async (artwork = artworkFixture) => { return await renderRelayTree({ - Component: ({ artwork: { images } }) => , + Component: ({ artwork: { images } }) => ( + + ), query: graphql` query ImageCarouselTestsQuery @raw_response_type { artwork(id: "unused") { @@ -139,8 +143,11 @@ describe("ImageCarouselFragmentContainer", () => { it("'selects' subsequent pagination dots as a result of scrolling", async () => { const wrapper = await getWrapper() - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const measurements = getMeasurements({ images: artworkFixture.images, boundingBox: { width: 375, height: 275 } }) + const measurements = getMeasurements({ + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + images: artworkFixture.images, + boundingBox: { width: 375, height: 275 }, + }) wrapper .find(FlatList) @@ -229,7 +236,11 @@ describe("Local Images and PaginationIndicator", () => { expect(wrapper.root.findAllByType(ScrollBar).length).toBe(0) }) it("Indicator can be a scrollbar", () => { - const wrapper = getWrapper({ paginationIndicatorType: "scrollBar", images: localImages, cardHeight: 275 }) + const wrapper = getWrapper({ + paginationIndicatorType: "scrollBar", + images: localImages, + cardHeight: 275, + }) expect(wrapper.root.findAllByType(PaginationDot).length).toBe(0) expect(wrapper.root.findByType(ScrollBar)).toBeDefined() }) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tsx index c1f83774e76..059ddee0fce 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarousel.tsx @@ -9,7 +9,11 @@ import { PixelRatio } from "react-native" import { createFragmentContainer, graphql } from "react-relay" import { ImageCarouselFullScreen } from "./FullScreen/ImageCarouselFullScreen" import { fitInside } from "./geometry" -import { ImageCarouselContext, ImageDescriptor, useNewImageCarouselContext } from "./ImageCarouselContext" +import { + ImageCarouselContext, + ImageDescriptor, + useNewImageCarouselContext, +} from "./ImageCarouselContext" import { ImageCarouselEmbedded } from "./ImageCarouselEmbedded" import { IndicatorType, PaginationIndicator } from "./ImageCarouselPaginationIndicator" @@ -48,7 +52,10 @@ export const ImageCarousel = (props: ImageCarouselProps) => { const screenDimensions = useScreenDimensions() const { cardHeight, onImageIndexChange } = props - const embeddedCardBoundingBox = { width: screenDimensions.width, height: isPad() ? 460 : cardHeight } + const embeddedCardBoundingBox = { + width: screenDimensions.width, + height: isPad() ? 460 : cardHeight, + } // TODO:- Deepzoom for local images? const disableDeepZoom = props.images.some((image) => isALocalImage(image.url)) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tests.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tests.tsx index f9e5789a508..c356d7ff86a 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tests.tsx @@ -10,13 +10,17 @@ const contextMock: Parameters[0] = { height: 5, width: 5, url: "a", - deepZoom: { image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } } }, + deepZoom: { + image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } }, + }, }, { height: 5, width: 5, url: "b", - deepZoom: { image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } } }, + deepZoom: { + image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } }, + }, }, ], } @@ -103,11 +107,17 @@ describe("image carousel context", () => { context.dispatch({ type: "IMAGE_INDEX_CHANGED", nextImageIndex: 1 }) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(context.embeddedFlatListRef.current.scrollToIndex).toHaveBeenCalledWith({ animated: false, index: 1 }) + expect(context.embeddedFlatListRef.current.scrollToIndex).toHaveBeenCalledWith({ + animated: false, + index: 1, + }) context.dispatch({ type: "IMAGE_INDEX_CHANGED", nextImageIndex: 0 }) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - expect(context.embeddedFlatListRef.current.scrollToIndex).toHaveBeenCalledWith({ animated: false, index: 0 }) + expect(context.embeddedFlatListRef.current.scrollToIndex).toHaveBeenCalledWith({ + animated: false, + index: 0, + }) }) it("tracks the imageIndex changes", () => { diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tsx index fdda3ed3960..df17b31641b 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselContext.tsx @@ -5,7 +5,10 @@ import { Animated, FlatList, View } from "react-native" import { useTracking } from "react-tracking" import { GlobalState, useGlobalState } from "../../../../utils/useGlobalState" -export type ImageDescriptor = Pick +export type ImageDescriptor = Pick< + ImageCarousel_images[number], + "deepZoom" | "height" | "width" | "url" +> export type ImageCarouselAction = | { @@ -32,7 +35,12 @@ export type ImageCarouselAction = nextZoomScale: number } -export type FullScreenState = "none" | "doing first render" | "animating entry transition" | "entered" | "exiting" +export type FullScreenState = + | "none" + | "doing first render" + | "animating entry transition" + | "entered" + | "exiting" export interface ImageCarouselContext { imageIndex: GlobalState @@ -87,7 +95,10 @@ export function useNewImageCarouselContext({ setIsZoomedCompletelyOut(true) if (fullScreenState.current !== "none") { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - embeddedFlatListRef.current.scrollToIndex({ index: action.nextImageIndex, animated: false }) + embeddedFlatListRef.current.scrollToIndex({ + index: action.nextImageIndex, + animated: false, + }) } // tslint:disable-next-line: no-unused-expression onImageIndexChange && onImageIndexChange(imageIndex.current) @@ -126,4 +137,6 @@ export function useNewImageCarouselContext({ ) } -export const ImageCarouselContext = React.createContext(null as any /* STRICTNESS_MIGRATION */) +export const ImageCarouselContext = React.createContext( + null as any /* STRICTNESS_MIGRATION */ +) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tests.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tests.tsx index ea5f2f89eef..5ec14d15fdf 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tests.tsx @@ -13,13 +13,17 @@ const contextMock: Parameters[0] = { height: 5, width: 5, url: "a", - deepZoom: { image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } } }, + deepZoom: { + image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } }, + }, }, { height: 5, width: 5, url: "b", - deepZoom: { image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } } }, + deepZoom: { + image: { url: "", format: "", tileSize: 300, size: { width: 302, height: 302 } }, + }, }, ], } diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tsx index d6cc447abd4..9499ec9111a 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselEmbedded.tsx @@ -22,7 +22,10 @@ export const ImageCarouselEmbedded: React.FC = ({ }) => { const screenDimensions = useScreenDimensions() - const embeddedCardBoundingBox = { width: screenDimensions.width, height: isPad() ? 460 : cardHeight } + const embeddedCardBoundingBox = { + width: screenDimensions.width, + height: isPad() ? 460 : cardHeight, + } const { images, @@ -72,7 +75,8 @@ export const ImageCarouselEmbedded: React.FC = ({ // this exists as a hack to get onPress functionality while the flat list is still coming to a stop after a swipe. // without this the user can tap the image to go fullscreen but nothing happens and it feels baaaad. const onResponderRelease = useCallback((ev: any) => { - const { touchBank, indexOfSingleActiveTouch, numberActiveTouches } = ev.touchHistory || ({} as any) + const { touchBank, indexOfSingleActiveTouch, numberActiveTouches } = + ev.touchHistory || ({} as any) if (numberActiveTouches !== 0) { return } @@ -97,7 +101,8 @@ export const ImageCarouselEmbedded: React.FC = ({ const duration = info.currentTimeStamp - info.startTimeStamp const distance = Math.sqrt( - Math.pow(info.currentPageX - info.startPageX, 2) + Math.pow(info.currentPageY - info.startPageY, 2) + Math.pow(info.currentPageX - info.startPageX, 2) + + Math.pow(info.currentPageY - info.startPageY, 2) ) if (distance > 5) { @@ -119,7 +124,11 @@ export const ImageCarouselEmbedded: React.FC = ({ ref={embeddedFlatListRef} showsHorizontalScrollIndicator={false} scrollEnabled={scrollEnabled} - getItemLayout={(_, index) => ({ index, offset: offsets[index], length: embeddedCardBoundingBox.width })} + getItemLayout={(_, index) => ({ + index, + offset: offsets[index], + length: embeddedCardBoundingBox.width, + })} snapToOffsets={offsets} // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 keyExtractor={(item) => item.url} diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselPaginationIndicator.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselPaginationIndicator.tsx index 047fe4b779c..5f69f729aea 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselPaginationIndicator.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageCarouselPaginationIndicator.tsx @@ -7,7 +7,9 @@ import { useSpringValue } from "./useSpringValue" export type IndicatorType = "dots" | "scrollBar" | undefined -export const PaginationIndicator: React.FC<{ indicatorType: IndicatorType }> = ({ indicatorType }) => { +export const PaginationIndicator: React.FC<{ indicatorType: IndicatorType }> = ({ + indicatorType, +}) => { if (indicatorType === "scrollBar") { return } @@ -28,7 +30,10 @@ const PaginationDots: React.FC = () => { ) } -export const PaginationDot: React.FC<{ diameter: number; index: number }> = ({ diameter, index }) => { +export const PaginationDot: React.FC<{ diameter: number; index: number }> = ({ + diameter, + index, +}) => { const { imageIndex } = useContext(ImageCarouselContext) imageIndex.useUpdates() const opacity = useSpringValue(imageIndex.current === index ? 1 : 0.1) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageWithLoadingState.tsx b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageWithLoadingState.tsx index 167efcd1b47..04d9476c732 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageWithLoadingState.tsx +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/ImageWithLoadingState.tsx @@ -18,29 +18,31 @@ interface ImageWithLoadingStateProps { * * @param param0 same as RN's Image props */ -export const ImageWithLoadingState = React.forwardRef((props, ref) => { - // When the image has loaded we want to fade it in, so we have a white overlay - // this assumes the image will be on a white backdrop. This component will - // need to be significantly refactored if it ever needs to be used with other - // color backgrounds - // show a loading spinner only after a short delay, if the image is taking a while to load - const { width, height, imageURL, onPress } = props - return ( - - - { - if (props.onLoad) { - props.onLoad() - } - }} - imageURL={imageURL} - aspectRatio={width / height} - style={{ width, height }} - highPriority={props.highPriority} - /> - - - ) -}) +export const ImageWithLoadingState = React.forwardRef( + (props, ref) => { + // When the image has loaded we want to fade it in, so we have a white overlay + // this assumes the image will be on a white backdrop. This component will + // need to be significantly refactored if it ever needs to be used with other + // color backgrounds + // show a loading spinner only after a short delay, if the image is taking a while to load + const { width, height, imageURL, onPress } = props + return ( + + + { + if (props.onLoad) { + props.onLoad() + } + }} + imageURL={imageURL} + aspectRatio={width / height} + style={{ width, height }} + highPriority={props.highPriority} + /> + + + ) + } +) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/geometry.ts b/src/lib/Scenes/Artwork/Components/ImageCarousel/geometry.ts index a4971119e2d..63021a9a373 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/geometry.ts +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/geometry.ts @@ -12,7 +12,10 @@ export interface Rect extends Size, Position {} // places a box (child) in the center of another (container), making the child 'fit' within the container // without overflowing or changing the child's aspect ratio -export function fitInside(container: Size, child: Size): Size & { marginHorizontal: number; marginVertical: number } { +export function fitInside( + container: Size, + child: Size +): Size & { marginHorizontal: number; marginVertical: number } { const aspectRatio = child.width / child.height // start out assuming that we need to constrain the image by height @@ -49,21 +52,30 @@ const MIN_MARGIN = 20 // given an input array of image sources, calculates the dimensions and positions of all the images on the carousel // rail. boundingBox is the maximum possible size that an image can occupy on the rail -export function getMeasurements({ images, boundingBox }: { images: ReadonlyArray; boundingBox: Size }) { +export function getMeasurements({ + images, + boundingBox, +}: { + images: ReadonlyArray + boundingBox: Size +}) { const result: ImageMeasurements[] = [] for (let i = 0; i < images.length; i++) { const { width, height, marginHorizontal, marginVertical } = fitInside(boundingBox, images[i]) // collapse adjacent margins to avoid excess white space between images - const marginLeft = i === 0 ? marginHorizontal : Math.max(marginHorizontal - result[i - 1].marginRight, 0) + const marginLeft = + i === 0 ? marginHorizontal : Math.max(marginHorizontal - result[i - 1].marginRight, 0) // make sure there's at least 20px between images const paddingLeft = i === 0 ? 0 : Math.max(0, MIN_MARGIN - marginLeft) // calculate cumulative scroll offset taking collapsed margins into account const cumulativeScrollOffset = - i === 0 ? 0 : result[i - 1].cumulativeScrollOffset + boundingBox.width - (marginHorizontal - marginLeft) + i === 0 + ? 0 + : result[i - 1].cumulativeScrollOffset + boundingBox.width - (marginHorizontal - marginLeft) result.push({ width, diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/useAnimatedValue.ts b/src/lib/Scenes/Artwork/Components/ImageCarousel/useAnimatedValue.ts index 2810e09cc39..5c816110366 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/useAnimatedValue.ts +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/useAnimatedValue.ts @@ -5,4 +5,5 @@ import { Animated } from "react-native" * Returns a stable Animated.Value. Does not update the value after mounting. * @param initialValue the initial value */ -export const useAnimatedValue = (initialValue: number) => useMemo(() => new Animated.Value(initialValue), []) +export const useAnimatedValue = (initialValue: number) => + useMemo(() => new Animated.Value(initialValue), []) diff --git a/src/lib/Scenes/Artwork/Components/ImageCarousel/useSpringValue.ts b/src/lib/Scenes/Artwork/Components/ImageCarousel/useSpringValue.ts index 7cac864b5d7..84c876976f6 100644 --- a/src/lib/Scenes/Artwork/Components/ImageCarousel/useSpringValue.ts +++ b/src/lib/Scenes/Artwork/Components/ImageCarousel/useSpringValue.ts @@ -12,7 +12,10 @@ import { useAnimatedValue } from "./useAnimatedValue" * @param currentValue * @param config */ -export const useSpringValue = (currentValue: number, config: Partial = {}) => { +export const useSpringValue = ( + currentValue: number, + config: Partial = {} +) => { const value = useAnimatedValue(currentValue) const anim = useRef() useEffect(() => { diff --git a/src/lib/Scenes/Artwork/Components/InstagramStoryViewShot.tsx b/src/lib/Scenes/Artwork/Components/InstagramStoryViewShot.tsx index 7ebc1663ae2..e4468403fe6 100644 --- a/src/lib/Scenes/Artwork/Components/InstagramStoryViewShot.tsx +++ b/src/lib/Scenes/Artwork/Components/InstagramStoryViewShot.tsx @@ -25,7 +25,12 @@ export interface InstagramStoryViewShotProps { title?: string } -export const InstagramStoryViewShot: React.FC = ({ shotRef, href, artist, title }) => { +export const InstagramStoryViewShot: React.FC = ({ + shotRef, + href, + artist, + title, +}) => { const debugInstagramShot = useDevToggle("DTShowInstagramShot") const { width, height } = useSizeToFitScreen({ width: InstagramStoryBackgroundDimensions.width, @@ -37,7 +42,11 @@ export const InstagramStoryViewShot: React.FC = ({ return ( - + { const formattedQuestions = inquiryState.inquiryQuestions.map((q: InquiryQuestionInput) => { if (q.questionID === "shipping_quote" && inquiryState.shippingLocation) { - const { city, coordinates, country, postalCode, state, stateCode } = inquiryState.shippingLocation + const { city, coordinates, country, postalCode, state, stateCode } = + inquiryState.shippingLocation const locationInput = { city, coordinates, diff --git a/src/lib/Scenes/Artwork/Components/PartnerCard.tests.tsx b/src/lib/Scenes/Artwork/Components/PartnerCard.tests.tsx index 8fe63516d74..adbe6cf01df 100644 --- a/src/lib/Scenes/Artwork/Components/PartnerCard.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/PartnerCard.tests.tsx @@ -62,7 +62,10 @@ describe("PartnerCard", () => { const component = mount( - + ) @@ -81,7 +84,10 @@ describe("PartnerCard", () => { const component = mount( - + ) @@ -101,7 +107,10 @@ describe("PartnerCard", () => { const component = mount( - + ) @@ -146,7 +155,10 @@ describe("PartnerCard", () => { const component = mount( - + ) @@ -164,7 +176,10 @@ describe("PartnerCard", () => { const component = mount( - + ) @@ -182,7 +197,10 @@ describe("PartnerCard", () => { const component = mount( - + ) diff --git a/src/lib/Scenes/Artwork/Components/PartnerCard.tsx b/src/lib/Scenes/Artwork/Components/PartnerCard.tsx index b7288948bc6..cd0116e29e0 100644 --- a/src/lib/Scenes/Artwork/Components/PartnerCard.tsx +++ b/src/lib/Scenes/Artwork/Components/PartnerCard.tsx @@ -87,7 +87,8 @@ export class PartnerCard extends React.Component { render() { const { artwork } = this.props const partner = artwork.partner! - const galleryOrBenefitAuction = artwork.sale && (artwork.sale.isBenefit || artwork.sale.isGalleryAuction) + const galleryOrBenefitAuction = + artwork.sale && (artwork.sale.isBenefit || artwork.sale.isGalleryAuction) if (partner.type === "Auction House" || galleryOrBenefitAuction) { return null } @@ -97,7 +98,9 @@ export class PartnerCard extends React.Component { locationNames = get(partner, (p) => limitWithCount(p.cities as any, 2), [])!.join(", ") } const showPartnerType = - partner.type === "Institution" || partner.type === "Gallery" || partner.type === "Institutional Seller" + partner.type === "Institution" || + partner.type === "Gallery" || + partner.type === "Institutional Seller" const partnerTypeDisplayText = partner.type === "Gallery" ? "gallery" : "institution" return ( diff --git a/src/lib/Scenes/Artwork/Components/RequestConditionReport-analytics.tests.tsx b/src/lib/Scenes/Artwork/Components/RequestConditionReport-analytics.tests.tsx index ffa6f278aef..02c2f46f164 100644 --- a/src/lib/Scenes/Artwork/Components/RequestConditionReport-analytics.tests.tsx +++ b/src/lib/Scenes/Artwork/Components/RequestConditionReport-analytics.tests.tsx @@ -96,7 +96,9 @@ it("tracks request condition report failure", async () => { ) const requestConditionReportComponent = trackingComponent.find("RequestConditionReport") - requestConditionReportComponent.instance().requestConditionReport = jest.fn().mockReturnValue(Promise.reject()) + requestConditionReportComponent.instance().requestConditionReport = jest + .fn() + .mockReturnValue(Promise.reject()) requestConditionReportComponent.update() const requestReportButton = requestConditionReportComponent.find(Button).at(0) requestReportButton.props().onPress() diff --git a/src/lib/Scenes/Artwork/Components/RequestConditionReport.tsx b/src/lib/Scenes/Artwork/Components/RequestConditionReport.tsx index 50c8b137e4c..9e5e29999db 100644 --- a/src/lib/Scenes/Artwork/Components/RequestConditionReport.tsx +++ b/src/lib/Scenes/Artwork/Components/RequestConditionReport.tsx @@ -11,7 +11,13 @@ import { Schema, track } from "lib/utils/track" import { Button, Flex } from "palette" import React from "react" import { View } from "react-native" -import { commitMutation, createFragmentContainer, graphql, QueryRenderer, RelayProp } from "react-relay" +import { + commitMutation, + createFragmentContainer, + graphql, + QueryRenderer, + RelayProp, +} from "react-relay" import { PayloadError } from "relay-runtime" interface RequestConditionReportProps { @@ -106,7 +112,12 @@ export class RequestConditionReport extends React.Component @@ -172,20 +183,23 @@ export const RequestConditionReportQueryRenderer: React.FC<{ ) } -export const RequestConditionReportFragmentContainer = createFragmentContainer(RequestConditionReport, { - me: graphql` - fragment RequestConditionReport_me on Me { - email - internalID - } - `, - artwork: graphql` - fragment RequestConditionReport_artwork on Artwork { - internalID - slug - saleArtwork { +export const RequestConditionReportFragmentContainer = createFragmentContainer( + RequestConditionReport, + { + me: graphql` + fragment RequestConditionReport_me on Me { + email internalID } - } - `, -}) + `, + artwork: graphql` + fragment RequestConditionReport_artwork on Artwork { + internalID + slug + saleArtwork { + internalID + } + } + `, + } +) diff --git a/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tests.tsx b/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tests.tsx index 97b33ae64ea..37656fe976c 100644 --- a/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tests.tsx +++ b/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tests.tsx @@ -2,7 +2,10 @@ import { goBack } from "lib/navigation/navigate" import { extractText } from "lib/tests/extractText" import { setupTestWrapper } from "lib/tests/setupTestWrapper" import { Button, Text } from "palette" -import { ARTWORK_ATTRIBUTION_CLASS_FAQ_QUERY, ArtworkAttributionClassFAQ } from "./ArtworkAttributionClassFAQ" +import { + ARTWORK_ATTRIBUTION_CLASS_FAQ_QUERY, + ArtworkAttributionClassFAQ, +} from "./ArtworkAttributionClassFAQ" jest.unmock("react-relay") @@ -58,7 +61,8 @@ const ATTRIBUTION_CLASSES = [ }, { name: "Made-to-order", - longDescription: "A piece that is made-to-order, taking into account the collector’s preferences.", + longDescription: + "A piece that is made-to-order, taking into account the collector’s preferences.", }, { name: "Reproduction", diff --git a/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tsx b/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tsx index 2d236d2875a..c4b4c9a8503 100644 --- a/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tsx +++ b/src/lib/Scenes/ArtworkAttributionClassFAQ/ArtworkAttributionClassFAQ.tsx @@ -38,7 +38,8 @@ export const ArtworkAttributionClassFAQ: React.FC = ({ artworkAttribution - Our partners are responsible for providing accurate classification information for all works. + Our partners are responsible for providing accurate classification information for all + works. diff --git a/src/lib/Scenes/Consignments/Components/FormElements.tsx b/src/lib/Scenes/Consignments/Components/FormElements.tsx index f6631a67126..42b1741bcd2 100644 --- a/src/lib/Scenes/Consignments/Components/FormElements.tsx +++ b/src/lib/Scenes/Consignments/Components/FormElements.tsx @@ -14,7 +14,10 @@ export const Form: React.FC<{ title?: string }> = (props) => ( /** An individual row inside the form */ export const Row: React.FC = ({ children, ...props }) => ( - + {children} ) diff --git a/src/lib/Scenes/Consignments/Components/ImageSelection.tests.tsx b/src/lib/Scenes/Consignments/Components/ImageSelection.tests.tsx index dc3e7c82aad..c6c906d55e4 100644 --- a/src/lib/Scenes/Consignments/Components/ImageSelection.tests.tsx +++ b/src/lib/Scenes/Consignments/Components/ImageSelection.tests.tsx @@ -6,7 +6,9 @@ import ImageSelection from "./ImageSelection" const uri = "https://d32dm0rphc51dk.cloudfront.net/WAlGHmjlxTn3USMllNt4rA/large.jpg" it("renders without throwing an error", () => { - renderWithWrappers() + renderWithWrappers( + + ) }) it("updates state on selection", () => { diff --git a/src/lib/Scenes/Consignments/Components/ImageSelection.tsx b/src/lib/Scenes/Consignments/Components/ImageSelection.tsx index 05f4adfd293..e969d13bdb8 100644 --- a/src/lib/Scenes/Consignments/Components/ImageSelection.tsx +++ b/src/lib/Scenes/Consignments/Components/ImageSelection.tsx @@ -17,7 +17,8 @@ const SelectedIndicator = styled.View` ` const Overlay = styled.View` - ${(p: { selected: boolean }) => p.selected && `border-width: 1; border-color: ${themeGet("colors.black60")}`}; + ${(p: { selected: boolean }) => + p.selected && `border-width: 1; border-color: ${themeGet("colors.black60")}`}; ` export interface ImageData { @@ -37,7 +38,9 @@ interface TakePhotoImageProps { } const SelectedIcon = () => ( - + ) @@ -98,7 +101,10 @@ const ImageForURI = (props: ImagePreviewProps) => { opacity: props.selected ? 0.5 : 1.0, }} > - + {props.selected ? : null} @@ -153,7 +159,9 @@ export default class ImageSelection extends React.Component { render() { const dimensionsWidth = Dimensions.get("window").width const isPad = dimensionsWidth > 700 - const data = isPad ? [TakePhotoID, ...this.props.data] : [TakePhotoID, ...this.props.data, BlankImageID] + const data = isPad + ? [TakePhotoID, ...this.props.data] + : [TakePhotoID, ...this.props.data, BlankImageID] return ( (props: SearchQueryProps) { returnKeyType: "search", value: props.query || "", onChangeText: props.onChangeText, - autoFocus: typeof jest === "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */, + autoFocus: + typeof jest === "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */, }} /> { paddingTop: 8, }} > - {props.text! /* STRICTNESS_MIGRATION */.value || props.text! /* STRICTNESS_MIGRATION */.placeholder} + {props.text! /* STRICTNESS_MIGRATION */.value || + props.text! /* STRICTNESS_MIGRATION */.placeholder} ) } diff --git a/src/lib/Scenes/Consignments/Components/Toggle.tsx b/src/lib/Scenes/Consignments/Components/Toggle.tsx index 99319ac3154..8433aabe0e9 100644 --- a/src/lib/Scenes/Consignments/Components/Toggle.tsx +++ b/src/lib/Scenes/Consignments/Components/Toggle.tsx @@ -65,7 +65,11 @@ const render = (props: ToggleProps) => { return ( {({ color }) => ( - + {selected ? props.left : ""} diff --git a/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tests.tsx b/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tests.tsx index 121b92356a1..1e2b065ba47 100644 --- a/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tests.tsx +++ b/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tests.tsx @@ -137,7 +137,12 @@ describe("RecentlySold", () => { }) function makeTargetSupply( - artworks: Array<{ artistNames?: string; realizedPrice?: string | null; slug?: string; internalID?: string }> + artworks: Array<{ + artistNames?: string + realizedPrice?: string | null + slug?: string + internalID?: string + }> ) { const items = artworks.map((artwork) => { return { diff --git a/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tsx b/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tsx index fb90aa2b6b0..6ecb40c64ad 100644 --- a/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tsx +++ b/src/lib/Scenes/Consignments/ConsignmentsHome/Components/RecentlySold.tsx @@ -34,7 +34,9 @@ export const RecentlySold: React.FC = ({ targetSupply, isLoad return null } - const recentlySoldArtworks = shuffle(microfunnelItems.map((x) => x?.artworksConnection?.edges?.[0]?.node)) + const recentlySoldArtworks = shuffle( + microfunnelItems.map((x) => x?.artworksConnection?.edges?.[0]?.node) + ) return ( @@ -55,7 +57,9 @@ export const RecentlySold: React.FC = ({ targetSupply, isLoad windowSize={3} data={recentlySoldArtworks} renderItem={({ item }) => { - const saleMessage = item?.realizedPrice ? `Sold for ${item?.realizedPrice}` : undefined + const saleMessage = item?.realizedPrice + ? `Sold for ${item?.realizedPrice}` + : undefined return ( = ({ environment }) => { +export const ConsignmentsHomeQueryRenderer: React.FC = ({ + environment, +}) => { return ( environment={environment || defaultEnvironment} diff --git a/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tests.tsx b/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tests.tsx index 4e552619e94..1d0c5ed41fa 100644 --- a/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tests.tsx @@ -96,8 +96,12 @@ describe("ConfirmContactInfo", () => { }) tree.root.findByType(Button).props.onPress() expect(env.mock.getAllOperations()).toHaveLength(1) - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("updateMyUserProfileMutation") - expect(env.mock.getMostRecentOperation().request.variables).toEqual({ input: { phone: "+1 (555) 890-2345" } }) + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "updateMyUserProfileMutation" + ) + expect(env.mock.getMostRecentOperation().request.variables).toEqual({ + input: { phone: "+1 (555) 890-2345" }, + }) }) it("shows an alert if something went wrong", async () => { @@ -113,7 +117,9 @@ describe("ConfirmContactInfo", () => { ) tree.root.findByType(Button).props.onPress() expect(env.mock.getAllOperations()).toHaveLength(1) - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("updateMyUserProfileMutation") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "updateMyUserProfileMutation" + ) expect(Alert.alert).not.toHaveBeenCalled() await act(() => { diff --git a/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tsx b/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tsx index bb323d9fe16..750a3977907 100644 --- a/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tsx +++ b/src/lib/Scenes/Consignments/Screens/ConfirmContactInfo.tsx @@ -82,7 +82,11 @@ const ConfirmContactInfo: React.FC<{ showSeparator={isInputFocused} > - + - Please verify your phone number so we can reach you about the status of your work. This info will also be - saved to your account. + Please verify your phone number so we can reach you about the status of your work. + This info will also be saved to your account. {me ? ( diff --git a/src/lib/Scenes/Consignments/Screens/Confirmation.tsx b/src/lib/Scenes/Consignments/Screens/Confirmation.tsx index c0af872164c..b70668d79c8 100644 --- a/src/lib/Scenes/Consignments/Screens/Confirmation.tsx +++ b/src/lib/Scenes/Consignments/Screens/Confirmation.tsx @@ -46,13 +46,19 @@ export default class Confirmation extends React.Component { submissionState: props.initialState || SubmissionTypes.Submitting, } - if (this.state.submissionState === SubmissionTypes.Submitting && props.submissionRequestValidationCheck) { + if ( + this.state.submissionState === SubmissionTypes.Submitting && + props.submissionRequestValidationCheck + ) { setTimeout(this.checkForSubmissionStatus.bind(this), 1000) } } componentDidMount = () => { - this.backButtonListener = BackHandler.addEventListener("hardwareBackPress", this.handleDismiss.bind(this)) + this.backButtonListener = BackHandler.addEventListener( + "hardwareBackPress", + this.handleDismiss.bind(this) + ) } componentWillUnmount = () => { @@ -79,7 +85,9 @@ export default class Confirmation extends React.Component { if (success === undefined) { setTimeout(this.checkForSubmissionStatus, 1000) } else { - const submissionState = success ? SubmissionTypes.SuccessfulSubmission : SubmissionTypes.FailedSubmission + const submissionState = success + ? SubmissionTypes.SuccessfulSubmission + : SubmissionTypes.FailedSubmission this.setState({ submissionState }) } } @@ -107,12 +115,13 @@ export default class Confirmation extends React.Component { - Our team of specialists are reviewing your work. You'll receive an email update once the status of your - submission changes. + Our team of specialists are reviewing your work. You'll receive an email update once + the status of your submission changes. - If your work is accepted, Artsy will gather competitive offers and guide you through the selling process. + If your work is accepted, Artsy will gather competitive offers and guide you through + the selling process. diff --git a/src/lib/Scenes/Consignments/Screens/Edition.tests.tsx b/src/lib/Scenes/Consignments/Screens/Edition.tests.tsx index 16953fcb16a..a5a85415f19 100644 --- a/src/lib/Scenes/Consignments/Screens/Edition.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Edition.tests.tsx @@ -8,7 +8,9 @@ import Edition from "./Edition" const nav = {} as any it("renders without throwing an error", () => { - const tree = renderWithWrappers( ""} />) + const tree = renderWithWrappers( + ""} /> + ) expect(tree.root.findAllByType(Text)).toHaveLength(0) }) diff --git a/src/lib/Scenes/Consignments/Screens/Edition.tsx b/src/lib/Scenes/Consignments/Screens/Edition.tsx index 22e92c7df93..e64d2dc3cc7 100644 --- a/src/lib/Scenes/Consignments/Screens/Edition.tsx +++ b/src/lib/Scenes/Consignments/Screens/Edition.tsx @@ -48,21 +48,35 @@ export default class Edition extends React.Component { updateCert = () => this.setState({ certificateOfAuth: !this.state.certificateOfAuth }) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - updateEditionSize = (text) => this.setState({ editionInfo: { ...this.state.editionInfo, size: text } }) + updateEditionSize = (text) => + this.setState({ editionInfo: { ...this.state.editionInfo, size: text } }) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - updateEditionNumber = (text) => this.setState({ editionInfo: { ...this.state.editionInfo, number: text } }) + updateEditionNumber = (text) => + this.setState({ editionInfo: { ...this.state.editionInfo, number: text } }) render() { return ( - Edition & Authenticity + + Edition & Authenticity +
- + Is this an edition? - + {this.state.editionInfo ? ( @@ -88,7 +102,12 @@ export default class Edition extends React.Component { ) : null} - + Is this work signed? diff --git a/src/lib/Scenes/Consignments/Screens/Location.tsx b/src/lib/Scenes/Consignments/Screens/Location.tsx index e5a02f66578..2c545896e08 100644 --- a/src/lib/Scenes/Consignments/Screens/Location.tsx +++ b/src/lib/Scenes/Consignments/Screens/Location.tsx @@ -47,7 +47,9 @@ export default class Location extends React.Component { placeid: result.id, }) - const response = await fetch("https://maps.googleapis.com/maps/api/place/details/json?" + queryString) + const response = await fetch( + "https://maps.googleapis.com/maps/api/place/details/json?" + queryString + ) const results = await response.json() // TODO: Add dedicated error handling to the maps response @@ -55,8 +57,10 @@ export default class Location extends React.Component { const { address_components } = results.result // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 const cityPlace = address_components.find((comp) => comp.types[0] === "locality") - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const statePlace = address_components.find((comp) => comp.types[0] === "administrative_area_level_1") + const statePlace = address_components.find( + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + (comp) => comp.types[0] === "administrative_area_level_1" + ) // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 const countryPlace = address_components.find((comp) => comp.types[0] === "country") @@ -85,7 +89,9 @@ export default class Location extends React.Component { input: query, }) - const response = await fetch("https://maps.googleapis.com/maps/api/place/autocomplete/json?" + queryString) + const response = await fetch( + "https://maps.googleapis.com/maps/api/place/autocomplete/json?" + queryString + ) const results = await response.json() this.setState({ diff --git a/src/lib/Scenes/Consignments/Screens/Metadata.tests.tsx b/src/lib/Scenes/Consignments/Screens/Metadata.tests.tsx index 5abef6696fc..099e0370b70 100644 --- a/src/lib/Scenes/Consignments/Screens/Metadata.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Metadata.tests.tsx @@ -24,13 +24,17 @@ describe("state", () => { it("is set up with empty consignment metadata", () => { const consignmentMetadata = {} as ConsignmentMetadata const tree = renderWithWrappers() - expect(tree.root.findByProps({ testID: "consigments-metatdata-title" }).props.text.value).toBeFalsy() + expect( + tree.root.findByProps({ testID: "consigments-metatdata-title" }).props.text.value + ).toBeFalsy() }) it("is set up with filled consignment metadata", () => { const tree = renderWithWrappers() - expect(tree.root.findByProps({ testID: "consigments-metatdata-title" }).props.text.value).toBeTruthy() + expect( + tree.root.findByProps({ testID: "consigments-metatdata-title" }).props.text.value + ).toBeTruthy() }) it("sets state correctly at init", () => { diff --git a/src/lib/Scenes/Consignments/Screens/Metadata.tsx b/src/lib/Scenes/Consignments/Screens/Metadata.tsx index 89147257f86..805569fdc6e 100644 --- a/src/lib/Scenes/Consignments/Screens/Metadata.tsx +++ b/src/lib/Scenes/Consignments/Screens/Metadata.tsx @@ -25,7 +25,10 @@ const categoryOptions = [ { name: "Sculpture", value: "SCULPTURE" }, { name: "Photography", value: "PHOTOGRAPHY" }, { name: "Print", value: "PRINT" }, - { name: "Drawing, Collage or other Work on Paper", value: "DRAWING_COLLAGE_OR_OTHER_WORK_ON_PAPER" }, + { + name: "Drawing, Collage or other Work on Paper", + value: "DRAWING_COLLAGE_OR_OTHER_WORK_ON_PAPER", + }, { name: "Mixed Media", value: "MIXED_MEDIA" }, { name: "Performance Art", value: "PERFORMANCE_ART" }, { name: "Installation", value: "INSTALLATION" }, @@ -133,7 +136,13 @@ export default class Metadata extends React.Component { } selectNextInput = () => { - const inputs = [this.yearInput, this.mediumInput, this.widthInput, this.heightInput, this.depthInput] + const inputs = [ + this.yearInput, + this.mediumInput, + this.widthInput, + this.heightInput, + this.depthInput, + ] for (const input of inputs) { // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 if (input && input.root && input.root.focus && !input.root.props.value) { @@ -161,7 +170,8 @@ export default class Metadata extends React.Component { returnKeyType: "next", autoFocus: this.state.title ? false - : typeof jest === "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */, + : typeof jest === + "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */, }} style={{ margin: 10 }} /> @@ -249,7 +259,12 @@ export default class Metadata extends React.Component { }} > Units - + diff --git a/src/lib/Scenes/Consignments/Screens/Overview-analytics.tests.tsx b/src/lib/Scenes/Consignments/Screens/Overview-analytics.tests.tsx index ae805e05441..3db839a3703 100644 --- a/src/lib/Scenes/Consignments/Screens/Overview-analytics.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Overview-analytics.tests.tsx @@ -15,7 +15,12 @@ beforeEach(jest.resetAllMocks) it("calls the draft created event", () => { const overviewComponent = shallow( - + ).dive() const overview = overviewComponent.dive().instance() @@ -33,7 +38,12 @@ it("calls the draft created event", () => { it("calls the draft created event", () => { const overviewComponent = shallow( - + ).dive() const overview = overviewComponent.dive().instance() diff --git a/src/lib/Scenes/Consignments/Screens/Overview-local-storage.tests.tsx b/src/lib/Scenes/Consignments/Screens/Overview-local-storage.tests.tsx index 1bfe4f4c62a..c12e42c69b1 100644 --- a/src/lib/Scenes/Consignments/Screens/Overview-local-storage.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Overview-local-storage.tests.tsx @@ -7,8 +7,12 @@ AsyncStorage.removeItem = jest.fn() import { Overview } from "./Overview" jest.mock("@react-native-community/cameraroll", () => jest.fn()) -jest.mock("../Submission/createConsignmentSubmission", () => ({ createConsignmentSubmission: jest.fn() })) -jest.mock("../Submission/updateConsignmentSubmission", () => ({ updateConsignmentSubmission: jest.fn() })) +jest.mock("../Submission/createConsignmentSubmission", () => ({ + createConsignmentSubmission: jest.fn(), +})) +jest.mock("../Submission/updateConsignmentSubmission", () => ({ + updateConsignmentSubmission: jest.fn(), +})) beforeEach(() => { jest.resetAllMocks() diff --git a/src/lib/Scenes/Consignments/Screens/Overview-uploading.tests.tsx b/src/lib/Scenes/Consignments/Screens/Overview-uploading.tests.tsx index a252906b189..55537847a96 100644 --- a/src/lib/Scenes/Consignments/Screens/Overview-uploading.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Overview-uploading.tests.tsx @@ -5,7 +5,9 @@ AsyncStorage.removeItem = jest.fn() import { Overview } from "./Overview" -jest.mock("../Submission/updateConsignmentSubmission", () => ({ updateConsignmentSubmission: jest.fn() })) +jest.mock("../Submission/updateConsignmentSubmission", () => ({ + updateConsignmentSubmission: jest.fn(), +})) import { updateConsignmentSubmission } from "../Submission/updateConsignmentSubmission" jest.mock("../Submission/uploadPhotoToGemini", () => ({ uploadImageAndPassToGemini: jest.fn() })) diff --git a/src/lib/Scenes/Consignments/Screens/Overview.tests.tsx b/src/lib/Scenes/Consignments/Screens/Overview.tests.tsx index 438a94ba5c5..640694567eb 100644 --- a/src/lib/Scenes/Consignments/Screens/Overview.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Overview.tests.tsx @@ -21,7 +21,9 @@ const route = {} as any const anything = expect.anything it("renders without throwing an error", () => { - renderWithWrappers() + renderWithWrappers( + + ) }) describe("Opening the right page", () => { @@ -79,7 +81,10 @@ describe("Updating State", () => { it("updates Location", () => { overview.updateLocation("Huddersfield", "Yorkshire", "UK") - expect(stateMock).toBeCalledWith({ location: { city: "Huddersfield", country: "UK", state: "Yorkshire" } }, update) + expect(stateMock).toBeCalledWith( + { location: { city: "Huddersfield", country: "UK", state: "Yorkshire" } }, + update + ) }) it("updates Artist", () => { diff --git a/src/lib/Scenes/Consignments/Screens/Overview.tsx b/src/lib/Scenes/Consignments/Screens/Overview.tsx index 7b8c9ae7ff4..d2ddf210cb9 100644 --- a/src/lib/Scenes/Consignments/Screens/Overview.tsx +++ b/src/lib/Scenes/Consignments/Screens/Overview.tsx @@ -62,7 +62,8 @@ export class Overview extends React.Component { } } - saveStateToLocalStorage = () => AsyncStorage.setItem(consignmentsStateKey, JSON.stringify(this.state)) + saveStateToLocalStorage = () => + AsyncStorage.setItem(consignmentsStateKey, JSON.stringify(this.state)) restoreFromLocalStorage = () => AsyncStorage.getItem(consignmentsStateKey, (_err, result) => { const results = (result && JSON.parse(result)) || {} @@ -112,10 +113,14 @@ export class Overview extends React.Component { }) goToLocationTapped = () => - this.props.navigator.push({ component: Location, passProps: { updateWithResult: this.updateLocation } }) + this.props.navigator.push({ + component: Location, + passProps: { updateWithResult: this.updateLocation }, + }) updateArtist = (result: ArtistResult) => this.updateStateAndMetaphysics({ artist: result }) - updateMetadata = (result: ConsignmentMetadata) => this.updateStateAndMetaphysics({ metadata: result }) + updateMetadata = (result: ConsignmentMetadata) => + this.updateStateAndMetaphysics({ metadata: result }) updateProvenance = (result: string) => this.updateStateAndMetaphysics({ provenance: result }) updateEdition = (result: ConsignmentSetup) => this.updateStateAndMetaphysics(result) updateLocation = (city: string, state: string, country: string) => @@ -150,18 +155,22 @@ export class Overview extends React.Component { } showUploadFailureAlert(error: Error) { - Alert.alert("Sorry, we couldn't upload your images.", "Please try again or contact consign@artsy.net for help.", [ - { - text: "Cancel", - style: "cancel", - }, - { - text: "Retry", - onPress: () => { - this.updateLocalStateAndMetaphysics() + Alert.alert( + "Sorry, we couldn't upload your images.", + "Please try again or contact consign@artsy.net for help.", + [ + { + text: "Cancel", + style: "cancel", + }, + { + text: "Retry", + onPress: () => { + this.updateLocalStateAndMetaphysics() + }, }, - }, - ]) + ] + ) console.log("src/Screens/Consignments/Screens/Overview.tsx", error) } @@ -185,7 +194,13 @@ export class Overview extends React.Component { const utmSource = this.props.params.utm_source const utmMedium = this.props.params.utm_medium const utmTerm = this.props.params.utm_term - await updateConsignmentSubmission({ ...submission, utmSource, utmTerm, utmMedium, state: "SUBMITTED" }) + await updateConsignmentSubmission({ + ...submission, + utmSource, + utmTerm, + utmMedium, + state: "SUBMITTED", + }) await AsyncStorage.removeItem(consignmentsStateKey) this.submissionDraftSubmitted() } catch (error) { @@ -221,7 +236,8 @@ export class Overview extends React.Component { uploadPhotosIfNeeded = async () => { const uploading = this.state.photos && this.state.photos.some((f) => f.uploading) - const toUpload = this.state.photos && this.state.photos.filter((f) => !f.uploaded && f.image.path) + const toUpload = + this.state.photos && this.state.photos.filter((f) => !f.uploaded && f.image.path) if (!uploading && toUpload && toUpload.length) { // Pull out the first in the queue and upload it const photo = toUpload[0] diff --git a/src/lib/Scenes/Consignments/Screens/Provenance.tests.tsx b/src/lib/Scenes/Consignments/Screens/Provenance.tests.tsx index 1d95c210288..546aa4d5717 100644 --- a/src/lib/Scenes/Consignments/Screens/Provenance.tests.tsx +++ b/src/lib/Scenes/Consignments/Screens/Provenance.tests.tsx @@ -38,7 +38,9 @@ describe("state", () => { provenance.textChanged("Acquired by my father somewhere") - expect(provenance.setState).toHaveBeenCalledWith({ provenance: "Acquired by my father somewhere" }) + expect(provenance.setState).toHaveBeenCalledWith({ + provenance: "Acquired by my father somewhere", + }) }) }) diff --git a/src/lib/Scenes/Consignments/Screens/Provenance.tsx b/src/lib/Scenes/Consignments/Screens/Provenance.tsx index ca788ec88ae..abec1f18c4f 100644 --- a/src/lib/Scenes/Consignments/Screens/Provenance.tsx +++ b/src/lib/Scenes/Consignments/Screens/Provenance.tsx @@ -53,7 +53,9 @@ export default class Provenance extends React.Component { value: this.state.provenance, placeholder: "Add notes about how you acquired the work. If you’re not sure add any details about how long you’ve owned the work.", - autoFocus: typeof jest === "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */, + autoFocus: + typeof jest === + "undefined" /* TODO: https://github.com/facebook/jest/issues/3707 */, }} /> diff --git a/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/ArtworkSubmitted.tsx b/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/ArtworkSubmitted.tsx index e189f9d1ab3..8321953aa9e 100644 --- a/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/ArtworkSubmitted.tsx +++ b/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/ArtworkSubmitted.tsx @@ -8,7 +8,9 @@ import { SubmitArtworkOverviewNavigationStack } from "./SubmitArtworkOverview" interface ArtworkSubmittedScreenNavigationProps extends StackScreenProps {} -export const ArtworkSubmittedScreen: React.FC = ({ navigation }) => { +export const ArtworkSubmittedScreen: React.FC = ({ + navigation, +}) => { return ( @@ -17,12 +19,13 @@ export const ArtworkSubmittedScreen: React.FC - We will email you within 1-3 days to confirm if your artwork has been accepted or not. In the meantime your - submission will appear in the feature, My Collection. + We will email you within 1-3 days to confirm if your artwork has been accepted or not. In + the meantime your submission will appear in the feature, My Collection. - With low fees, informed pricing, and multiple sales options, why not submit another piece with Artsy. + With low fees, informed pricing, and multiple sales options, why not submit another piece + with Artsy. diff --git a/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/SubmitArtworkOverview.tsx b/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/SubmitArtworkOverview.tsx index 58e92ec9264..48942f5330f 100644 --- a/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/SubmitArtworkOverview.tsx +++ b/src/lib/Scenes/Consignments/Screens/SubmitArtworkOverview/SubmitArtworkOverview.tsx @@ -12,7 +12,9 @@ import { UploadPhotos } from "./UploadPhotos/UploadPhotos" interface SubmitArtworkScreenNavigationProps extends StackScreenProps {} -export const SubmitArtworkScreen: React.FC = ({ navigation }) => { +export const SubmitArtworkScreen: React.FC = ({ + navigation, +}) => { const items = [ { overtitle: "Step 1 of 3", diff --git a/src/lib/Scenes/Consignments/Submission/Gemini/createGeminiAssetWithS3Credentials.ts b/src/lib/Scenes/Consignments/Submission/Gemini/createGeminiAssetWithS3Credentials.ts index c7c5d339e94..6b34df398f8 100644 --- a/src/lib/Scenes/Consignments/Submission/Gemini/createGeminiAssetWithS3Credentials.ts +++ b/src/lib/Scenes/Consignments/Submission/Gemini/createGeminiAssetWithS3Credentials.ts @@ -9,7 +9,9 @@ export const createGeminiAssetWithS3Credentials = (input: CreateGeminiEntryForAs return new Promise((resolve, reject) => { commitMutation(defaultEnvironment, { mutation: graphql` - mutation createGeminiAssetWithS3CredentialsMutation($input: CreateGeminiEntryForAssetInput!) { + mutation createGeminiAssetWithS3CredentialsMutation( + $input: CreateGeminiEntryForAssetInput! + ) { createGeminiEntryForAsset(input: $input) { asset { token diff --git a/src/lib/Scenes/Consignments/Submission/Gemini/getGeminiCredentialsForEnvironment.ts b/src/lib/Scenes/Consignments/Submission/Gemini/getGeminiCredentialsForEnvironment.ts index ac7cfed818d..b8305a6057c 100644 --- a/src/lib/Scenes/Consignments/Submission/Gemini/getGeminiCredentialsForEnvironment.ts +++ b/src/lib/Scenes/Consignments/Submission/Gemini/getGeminiCredentialsForEnvironment.ts @@ -10,11 +10,15 @@ export type AssetCredentials = // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 getGeminiCredentialsForEnvironmentMutationResponse["requestCredentialsForAssetUpload"]["asset"] -export const getGeminiCredentialsForEnvironment = (input: RequestCredentialsForAssetUploadInput) => { +export const getGeminiCredentialsForEnvironment = ( + input: RequestCredentialsForAssetUploadInput +) => { return new Promise((resolve, reject) => { commitMutation(defaultEnvironment, { mutation: graphql` - mutation getGeminiCredentialsForEnvironmentMutation($input: RequestCredentialsForAssetUploadInput!) { + mutation getGeminiCredentialsForEnvironmentMutation( + $input: RequestCredentialsForAssetUploadInput! + ) { requestCredentialsForAssetUpload(input: $input) { asset { signature diff --git a/src/lib/Scenes/Consignments/Submission/consignmentSetupToSubmission.ts b/src/lib/Scenes/Consignments/Submission/consignmentSetupToSubmission.ts index a5067923b05..a46c67a1aee 100644 --- a/src/lib/Scenes/Consignments/Submission/consignmentSetupToSubmission.ts +++ b/src/lib/Scenes/Consignments/Submission/consignmentSetupToSubmission.ts @@ -17,7 +17,8 @@ export const consignmentSetupToMutationInput = (submission: ConsignmentSetup) => // Optional authenticityCertificate: submission.certificateOfAuth, category: submission.metadata ? submission.metadata.category : undefined, - depth: submission.metadata && submission.metadata.depth && submission.metadata.depth.toString(), + depth: + submission.metadata && submission.metadata.depth && submission.metadata.depth.toString(), dimensionsMetric: submission.metadata && submission.metadata.unit, edition: !!submission.editionInfo, editionNumber: submission.editionInfo && submission.editionInfo.number, diff --git a/src/lib/Scenes/Consignments/Submission/geminiUploadToS3.ts b/src/lib/Scenes/Consignments/Submission/geminiUploadToS3.ts index d11abbcb23d..b47d8d1de36 100644 --- a/src/lib/Scenes/Consignments/Submission/geminiUploadToS3.ts +++ b/src/lib/Scenes/Consignments/Submission/geminiUploadToS3.ts @@ -14,7 +14,12 @@ export interface S3UploadResponse { declare var FormData: any declare var XMLHttpRequest: any -export const uploadFileToS3 = (file: string, acl: string, asset: AssetCredentials, filename?: string) => +export const uploadFileToS3 = ( + file: string, + acl: string, + asset: AssetCredentials, + filename?: string +) => new Promise((resolve, reject) => { const formData = new FormData() const geminiKey = asset.policyDocument.conditions.geminiKey diff --git a/src/lib/Scenes/Consignments/Submission/uploadPhotoToGemini.ts b/src/lib/Scenes/Consignments/Submission/uploadPhotoToGemini.ts index bb0dfcabfee..80b6f3a5f66 100644 --- a/src/lib/Scenes/Consignments/Submission/uploadPhotoToGemini.ts +++ b/src/lib/Scenes/Consignments/Submission/uploadPhotoToGemini.ts @@ -6,7 +6,11 @@ import { uploadFileToS3, } from "./geminiUploadToS3" -export const uploadImageAndPassToGemini = async (file: string, acl: string, submissionID: string) => { +export const uploadImageAndPassToGemini = async ( + file: string, + acl: string, + submissionID: string +) => { const convectionKey = await getConvectionGeminiKey() if (!convectionKey) { diff --git a/src/lib/Scenes/Consignments/Typography/index.tsx b/src/lib/Scenes/Consignments/Typography/index.tsx index 7c9d7e3cdfb..676635f1f0a 100644 --- a/src/lib/Scenes/Consignments/Typography/index.tsx +++ b/src/lib/Scenes/Consignments/Typography/index.tsx @@ -35,7 +35,12 @@ const Subtitle: React.FC = (props) => { const BodyText: React.FC = (props) => { const { color } = useTheme() const children: string = (props as any).children - const style = [styles.bodyDefault, { color: color("black30") }, props.style || {}, styles.bodyRequired] + const style = [ + styles.bodyDefault, + { color: color("black30") }, + props.style || {}, + styles.bodyRequired, + ] return ( {children} @@ -46,7 +51,12 @@ const BodyText: React.FC = (props) => { const SmallPrint: React.FC = (props) => { const { color } = useTheme() const children: string = (props as any).children - const style = [styles.smallPrintDefault, { color: color("black30") }, props.style || {}, styles.smallPrintRequired] + const style = [ + styles.smallPrintDefault, + { color: color("black30") }, + props.style || {}, + styles.smallPrintRequired, + ] return ( {children} diff --git a/src/lib/Scenes/Fair/Components/FairArtworks.tsx b/src/lib/Scenes/Fair/Components/FairArtworks.tsx index 104e17b4670..fd39c186494 100644 --- a/src/lib/Scenes/Fair/Components/FairArtworks.tsx +++ b/src/lib/Scenes/Fair/Components/FairArtworks.tsx @@ -39,13 +39,21 @@ export const FairArtworks: React.FC = ({ const artworks = fair.fairArtworks! const artworksTotal = artworks?.counts?.total ?? 0 - const setInitialFilterStateAction = ArtworksFiltersStore.useStoreActions((state) => state.setInitialFilterStateAction) - const setFiltersCountAction = ArtworksFiltersStore.useStoreActions((state) => state.setFiltersCountAction) + const setInitialFilterStateAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setInitialFilterStateAction + ) + const setFiltersCountAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setFiltersCountAction + ) const counts = ArtworksFiltersStore.useStoreState((state) => state.counts) - const dispatchFollowedArtistCount = (followedArtistCount || artworks?.counts?.followedArtists) ?? 0 + const dispatchFollowedArtistCount = + (followedArtistCount || artworks?.counts?.followedArtists) ?? 0 const artworkAggregations = ((aggregations || artworks?.aggregations) ?? []) as aggregationsType - const dispatchAggregations = aggregationsWithFollowedArtists(dispatchFollowedArtistCount, artworkAggregations) + const dispatchAggregations = aggregationsWithFollowedArtists( + dispatchFollowedArtistCount, + artworkAggregations + ) useArtworkFilters({ relay, @@ -78,7 +86,11 @@ export const FairArtworks: React.FC = ({ if (artworksTotal === 0) { return ( - + ) } diff --git a/src/lib/Scenes/Fair/Components/FairCollections.tsx b/src/lib/Scenes/Fair/Components/FairCollections.tsx index 3a5fd8d96cc..09db0210d8a 100644 --- a/src/lib/Scenes/Fair/Components/FairCollections.tsx +++ b/src/lib/Scenes/Fair/Components/FairCollections.tsx @@ -61,7 +61,12 @@ export const FairCollections: React.FC = ({ fair, ...rest navigate(`/collection/${collection.slug}`) }} > - + ) }} diff --git a/src/lib/Scenes/Fair/Components/FairEditorial.tsx b/src/lib/Scenes/Fair/Components/FairEditorial.tsx index 4b5118a35dd..02a2fd1eabb 100644 --- a/src/lib/Scenes/Fair/Components/FairEditorial.tsx +++ b/src/lib/Scenes/Fair/Components/FairEditorial.tsx @@ -36,7 +36,14 @@ export const FairEditorial: React.FC = ({ fair, ...rest }) = return ( - + Related Reading {(fair.articles.totalCount ?? 0) > 5 && ( diff --git a/src/lib/Scenes/Fair/Components/FairEditorialShare.tsx b/src/lib/Scenes/Fair/Components/FairEditorialShare.tsx index 058a602db24..171b6744a36 100644 --- a/src/lib/Scenes/Fair/Components/FairEditorialShare.tsx +++ b/src/lib/Scenes/Fair/Components/FairEditorialShare.tsx @@ -7,7 +7,11 @@ interface FairEditorialShareProps extends BoxProps { url: string } -export const FairEditorialShare: React.FC = ({ subject, url, ...rest }) => ( +export const FairEditorialShare: React.FC = ({ + subject, + url, + ...rest +}) => ( { diff --git a/src/lib/Scenes/Fair/Components/FairExhibitorRail.tsx b/src/lib/Scenes/Fair/Components/FairExhibitorRail.tsx index ecdd5964e9b..4c1f08ed6ac 100644 --- a/src/lib/Scenes/Fair/Components/FairExhibitorRail.tsx +++ b/src/lib/Scenes/Fair/Components/FairExhibitorRail.tsx @@ -93,7 +93,11 @@ const FairExhibitorRail: React.FC = ({ show }) => { useSquareAspectRatio artistNames={item?.artistNames} saleMessage={item && saleMessageOrBidInfo({ artwork: item, isSmallTile: true })} - urgencyTag={item?.sale?.isAuction && !item?.sale?.isClosed ? getUrgencyTag(item?.sale?.endAt) : null} + urgencyTag={ + item?.sale?.isAuction && !item?.sale?.isClosed + ? getUrgencyTag(item?.sale?.endAt) + : null + } /> ) }} diff --git a/src/lib/Scenes/Fair/Components/FairFollowedArtistsRail.tsx b/src/lib/Scenes/Fair/Components/FairFollowedArtistsRail.tsx index c71b9288bfc..afaf24194e5 100644 --- a/src/lib/Scenes/Fair/Components/FairFollowedArtistsRail.tsx +++ b/src/lib/Scenes/Fair/Components/FairFollowedArtistsRail.tsx @@ -13,7 +13,10 @@ interface FairFollowedArtistsRailProps { fair: FairFollowedArtistsRail_fair } -export const FairFollowedArtistsRail: React.FC = ({ fair, ...rest }) => { +export const FairFollowedArtistsRail: React.FC = ({ + fair, + ...rest +}) => { if (!fair.followedArtistArtworks?.edges?.length) { return null } @@ -92,21 +95,27 @@ export const FairFollowedArtistsRail: React.FC = ( ) } -export const FairFollowedArtistsRailFragmentContainer = createFragmentContainer(FairFollowedArtistsRail, { - fair: graphql` - fragment FairFollowedArtistsRail_fair on Fair { - internalID - slug - followedArtistArtworks: filterArtworksConnection(first: 20, input: { includeArtworksByFollowedArtists: true }) { - edges { - artwork: node { - id - internalID - slug - ...ArtworkTileRailCard_artwork +export const FairFollowedArtistsRailFragmentContainer = createFragmentContainer( + FairFollowedArtistsRail, + { + fair: graphql` + fragment FairFollowedArtistsRail_fair on Fair { + internalID + slug + followedArtistArtworks: filterArtworksConnection( + first: 20 + input: { includeArtworksByFollowedArtists: true } + ) { + edges { + artwork: node { + id + internalID + slug + ...ArtworkTileRailCard_artwork + } } } } - } - `, -}) + `, + } +) diff --git a/src/lib/Scenes/Fair/Components/FairHeader.tsx b/src/lib/Scenes/Fair/Components/FairHeader.tsx index 9e44fbcf4fc..4d86a48b1ed 100644 --- a/src/lib/Scenes/Fair/Components/FairHeader.tsx +++ b/src/lib/Scenes/Fair/Components/FairHeader.tsx @@ -52,7 +52,11 @@ export const FairHeader: React.FC = ({ fair }) => { {!!image ? ( - + {!!profileImageUrl && ( = ({ fair }) => { bottom={0} left={2} > - + )} @@ -77,7 +86,9 @@ export const FairHeader: React.FC = ({ fair }) => { {name} - {!!previewText && } + {!!previewText && ( + + )} {!!canShowMoreInfoLink && ( navigate(`/fair/${slug}/info`)}> diff --git a/src/lib/Scenes/Fair/Components/FairTiming.tsx b/src/lib/Scenes/Fair/Components/FairTiming.tsx index 6b67855e793..384ca7551e8 100644 --- a/src/lib/Scenes/Fair/Components/FairTiming.tsx +++ b/src/lib/Scenes/Fair/Components/FairTiming.tsx @@ -9,7 +9,9 @@ interface FairTimingProps { fair: FairTiming_fair } -export const FairTiming: React.FC = ({ fair: { exhibitionPeriod, startAt, endAt } }) => { +export const FairTiming: React.FC = ({ + fair: { exhibitionPeriod, startAt, endAt }, +}) => { return ( diff --git a/src/lib/Scenes/Fair/Fair.tests.tsx b/src/lib/Scenes/Fair/Fair.tests.tsx index 3d593912f1b..db80e58ac89 100644 --- a/src/lib/Scenes/Fair/Fair.tests.tsx +++ b/src/lib/Scenes/Fair/Fair.tests.tsx @@ -50,7 +50,9 @@ describe("Fair", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Fair/Fair.tsx b/src/lib/Scenes/Fair/Fair.tsx index 3ef6fa2c26b..91bf8ed34bc 100644 --- a/src/lib/Scenes/Fair/Fair.tsx +++ b/src/lib/Scenes/Fair/Fair.tsx @@ -220,7 +220,9 @@ export const Fair: React.FC = ({ fair }) => { activeTab={activeTab} tabs={tabs} /> - {tabToShow?.label === "Artworks" && } + {tabToShow?.label === "Artworks" && ( + + )} ) } @@ -277,7 +279,10 @@ export const FairFragmentContainer = createFragmentContainer(Fair, { artworks partnerShows } - followedArtistArtworks: filterArtworksConnection(first: 20, input: { includeArtworksByFollowedArtists: true }) { + followedArtistArtworks: filterArtworksConnection( + first: 20 + input: { includeArtworksByFollowedArtists: true } + ) { edges { __typename } diff --git a/src/lib/Scenes/Fair/FairAllFollowedArtists.tests.tsx b/src/lib/Scenes/Fair/FairAllFollowedArtists.tests.tsx index aaf3c6c6648..f7095931f57 100644 --- a/src/lib/Scenes/Fair/FairAllFollowedArtists.tests.tsx +++ b/src/lib/Scenes/Fair/FairAllFollowedArtists.tests.tsx @@ -5,7 +5,10 @@ import { graphql, QueryRenderer } from "react-relay" import { act } from "react-test-renderer" import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils" import { FairArtworksFragmentContainer } from "./Components/FairArtworks" -import { FairAllFollowedArtists, FairAllFollowedArtistsFragmentContainer } from "./FairAllFollowedArtists" +import { + FairAllFollowedArtists, + FairAllFollowedArtistsFragmentContainer, +} from "./FairAllFollowedArtists" jest.unmock("react-relay") @@ -32,7 +35,12 @@ describe("FairAllFollowedArtists", () => { variables={{ fairID: "art-basel-hong-kong-2019" }} render={({ props, error }) => { if (props?.fair && props?.fairForFilters) { - return + return ( + + ) } else if (error) { console.log(error) } @@ -43,7 +51,9 @@ describe("FairAllFollowedArtists", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -56,7 +66,9 @@ describe("FairAllFollowedArtists", () => { it("renders a grid of artworks in the fair filtered by artists the user follows", () => { const wrapper = getWrapper() expect(wrapper.root.findAllByType(FairArtworksFragmentContainer)).toHaveLength(1) - expect(wrapper.root.findAllByType(FairArtworksFragmentContainer)[0].props.initiallyAppliedFilter).toStrictEqual([ + expect( + wrapper.root.findAllByType(FairArtworksFragmentContainer)[0].props.initiallyAppliedFilter + ).toStrictEqual([ { displayText: "All Artists I Follow", paramName: "includeArtworksByFollowedArtists", diff --git a/src/lib/Scenes/Fair/FairAllFollowedArtists.tsx b/src/lib/Scenes/Fair/FairAllFollowedArtists.tsx index 659e351ed66..427f1f35563 100644 --- a/src/lib/Scenes/Fair/FairAllFollowedArtists.tsx +++ b/src/lib/Scenes/Fair/FairAllFollowedArtists.tsx @@ -1,8 +1,16 @@ import { FairAllFollowedArtists_fair } from "__generated__/FairAllFollowedArtists_fair.graphql" import { FairAllFollowedArtists_fairForFilters } from "__generated__/FairAllFollowedArtists_fairForFilters.graphql" import { FairAllFollowedArtistsQuery } from "__generated__/FairAllFollowedArtistsQuery.graphql" -import { AnimatedArtworkFilterButton, ArtworkFilterNavigator, FilterModalMode } from "lib/Components/ArtworkFilter" -import { Aggregations, FilterArray, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" +import { + AnimatedArtworkFilterButton, + ArtworkFilterNavigator, + FilterModalMode, +} from "lib/Components/ArtworkFilter" +import { + Aggregations, + FilterArray, + FilterParamName, +} from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { defaultEnvironment } from "lib/relay/createEnvironment" import { PlaceholderGrid, PlaceholderText } from "lib/utils/placeholders" @@ -18,7 +26,10 @@ interface FairAllFollowedArtistsProps { fairForFilters: FairAllFollowedArtists_fairForFilters } -export const FairAllFollowedArtists: React.FC = ({ fair, fairForFilters }) => { +export const FairAllFollowedArtists: React.FC = ({ + fair, + fairForFilters, +}) => { const [isFilterArtworksModalVisible, setFilterArtworkModalVisible] = useState(false) const handleFilterArtworksModal = () => { setFilterArtworkModalVisible(!isFilterArtworksModalVisible) @@ -62,44 +73,57 @@ export const FairAllFollowedArtists: React.FC = ({ ) } -export const FairAllFollowedArtistsFragmentContainer = createFragmentContainer(FairAllFollowedArtists, { - fair: graphql` - fragment FairAllFollowedArtists_fair on Fair { - internalID - slug - ...FairArtworks_fair @arguments(input: { includeArtworksByFollowedArtists: true, sort: "-decayed_merch" }) - } - `, - /** - * Filter aggregations are normally dynamic according to applied filters. - * Because of the `includeArtworksByFollowedArtists` argument used above, the artwork grid is intially scoped to only - * include works by followed artists. - * The filter options become incomplete if that option is later disabled in the filter menu. - * To compensate, we are querying for the complete set below without the `includeArtworksByFollowedArtists` - * argument so that the complete set of filters is available. - */ - fairForFilters: graphql` - fragment FairAllFollowedArtists_fairForFilters on Fair { - filterArtworksConnection( - first: 0 - aggregations: [COLOR, DIMENSION_RANGE, PARTNER, MAJOR_PERIOD, MEDIUM, PRICE_RANGE, FOLLOWED_ARTISTS, ARTIST] - ) { - aggregations { - slice - counts { - count - name - value +export const FairAllFollowedArtistsFragmentContainer = createFragmentContainer( + FairAllFollowedArtists, + { + fair: graphql` + fragment FairAllFollowedArtists_fair on Fair { + internalID + slug + ...FairArtworks_fair + @arguments(input: { includeArtworksByFollowedArtists: true, sort: "-decayed_merch" }) + } + `, + /** + * Filter aggregations are normally dynamic according to applied filters. + * Because of the `includeArtworksByFollowedArtists` argument used above, the artwork grid is intially scoped to only + * include works by followed artists. + * The filter options become incomplete if that option is later disabled in the filter menu. + * To compensate, we are querying for the complete set below without the `includeArtworksByFollowedArtists` + * argument so that the complete set of filters is available. + */ + fairForFilters: graphql` + fragment FairAllFollowedArtists_fairForFilters on Fair { + filterArtworksConnection( + first: 0 + aggregations: [ + COLOR + DIMENSION_RANGE + PARTNER + MAJOR_PERIOD + MEDIUM + PRICE_RANGE + FOLLOWED_ARTISTS + ARTIST + ] + ) { + aggregations { + slice + counts { + count + name + value + } } - } - counts { - followedArtists + counts { + followedArtists + } } } - } - `, -}) + `, + } +) export const FairAllFollowedArtistsQueryRenderer: React.FC<{ fairID: string }> = ({ fairID }) => { return ( diff --git a/src/lib/Scenes/Fair/FairArticles.tsx b/src/lib/Scenes/Fair/FairArticles.tsx index 4cef6d90a02..86f9643ba57 100644 --- a/src/lib/Scenes/Fair/FairArticles.tsx +++ b/src/lib/Scenes/Fair/FairArticles.tsx @@ -87,7 +87,11 @@ export const FairArticles: React.FC = ({ fair, relay }) => { {heroArticle!.publishedAt} - + @@ -120,7 +124,11 @@ export const FairArticles: React.FC = ({ fair, relay }) => { {article!.publishedAt} - + ) @@ -157,7 +165,8 @@ export const FairArticlesPaginationContainer = createPaginationContainer( FairArticles, { fair: graphql` - fragment FairArticles_fair on Fair @argumentDefinitions(first: { type: "Int" }, after: { type: "String" }) { + fragment FairArticles_fair on Fair + @argumentDefinitions(first: { type: "Int" }, after: { type: "String" }) { slug articlesConnection(first: $first, after: $after, inEditorialFeed: true) @connection(key: "FairArticlesQuery_articlesConnection") { diff --git a/src/lib/Scenes/Fair/FairArtworks.tests.tsx b/src/lib/Scenes/Fair/FairArtworks.tests.tsx index 76ee82cf967..418c483cbb4 100644 --- a/src/lib/Scenes/Fair/FairArtworks.tests.tsx +++ b/src/lib/Scenes/Fair/FairArtworks.tests.tsx @@ -44,7 +44,9 @@ describe("FairArtworks", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } diff --git a/src/lib/Scenes/Fair/FairBMWArtActivation.tests.tsx b/src/lib/Scenes/Fair/FairBMWArtActivation.tests.tsx index cf9f92f0d32..5c6d093c8dd 100644 --- a/src/lib/Scenes/Fair/FairBMWArtActivation.tests.tsx +++ b/src/lib/Scenes/Fair/FairBMWArtActivation.tests.tsx @@ -1,6 +1,9 @@ import { extractText } from "lib/tests/extractText" import { setupTestWrapper } from "lib/tests/setupTestWrapper" -import { FAIR_BMW_ART_ACTIVATION_QUERY, FairBMWArtActivationFragmentContainer } from "./FairBMWArtActivation" +import { + FAIR_BMW_ART_ACTIVATION_QUERY, + FairBMWArtActivationFragmentContainer, +} from "./FairBMWArtActivation" jest.unmock("react-relay") diff --git a/src/lib/Scenes/Fair/FairBMWArtActivation.tsx b/src/lib/Scenes/Fair/FairBMWArtActivation.tsx index e09757198ba..b93502aeef9 100644 --- a/src/lib/Scenes/Fair/FairBMWArtActivation.tsx +++ b/src/lib/Scenes/Fair/FairBMWArtActivation.tsx @@ -90,7 +90,10 @@ export class FairBMWArtActivation extends React.Component { } } -function eventProps(actionName: Schema.ActionNames, actionType: Schema.ActionTypes = Schema.ActionTypes.Tap) { +function eventProps( + actionName: Schema.ActionNames, + actionType: Schema.ActionTypes = Schema.ActionTypes.Tap +) { return (props: Props) => ({ action_name: actionName, action_type: actionType, diff --git a/src/lib/Scenes/Fair/FairCollections.tests.tsx b/src/lib/Scenes/Fair/FairCollections.tests.tsx index 49002f1f6f4..e656f281c57 100644 --- a/src/lib/Scenes/Fair/FairCollections.tests.tsx +++ b/src/lib/Scenes/Fair/FairCollections.tests.tsx @@ -41,7 +41,9 @@ describe("FairCollections", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } diff --git a/src/lib/Scenes/Fair/FairEditorial.tests.tsx b/src/lib/Scenes/Fair/FairEditorial.tests.tsx index f96d030fbca..17aa86dfd2b 100644 --- a/src/lib/Scenes/Fair/FairEditorial.tests.tsx +++ b/src/lib/Scenes/Fair/FairEditorial.tests.tsx @@ -41,7 +41,9 @@ describe("FairEditorial", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } @@ -120,7 +122,8 @@ describe("FairEditorial", () => { context_screen_owner_slug: "art-basel-hong-kong-2020", destination_screen_owner_type: "article", destination_screen_owner_id: "xyz123", - destination_screen_owner_slug: "artsy-editorial-sold-art-basel-hong-kongs-online-viewing-rooms", + destination_screen_owner_slug: + "artsy-editorial-sold-art-basel-hong-kongs-online-viewing-rooms", type: "thumbnail", }) }) diff --git a/src/lib/Scenes/Fair/FairEmptyState.tests.tsx b/src/lib/Scenes/Fair/FairEmptyState.tests.tsx index 4353e1bf351..06577a73c54 100644 --- a/src/lib/Scenes/Fair/FairEmptyState.tests.tsx +++ b/src/lib/Scenes/Fair/FairEmptyState.tests.tsx @@ -30,7 +30,9 @@ describe("FairEmptyState", () => { }) it("renders correctly when the fair is in the future", () => { - const wrapper = getWrapper({ Fair: () => ({ isActive: false, endAt: DateTime.local().plus({ days: 1 }) }) }) + const wrapper = getWrapper({ + Fair: () => ({ isActive: false, endAt: DateTime.local().plus({ days: 1 }) }), + }) expect(extractText(wrapper.root)).toEqual( "This fair is currently unavailable. Please check back closer to the fair for artworks." ) diff --git a/src/lib/Scenes/Fair/FairExhibitorRail.tests.tsx b/src/lib/Scenes/Fair/FairExhibitorRail.tests.tsx index c133056e0bd..7bda81a26a4 100644 --- a/src/lib/Scenes/Fair/FairExhibitorRail.tests.tsx +++ b/src/lib/Scenes/Fair/FairExhibitorRail.tests.tsx @@ -43,7 +43,9 @@ describe("FairExhibitors", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } diff --git a/src/lib/Scenes/Fair/FairExhibitors.tests.tsx b/src/lib/Scenes/Fair/FairExhibitors.tests.tsx index c7809b7b752..304208f89b9 100644 --- a/src/lib/Scenes/Fair/FairExhibitors.tests.tsx +++ b/src/lib/Scenes/Fair/FairExhibitors.tests.tsx @@ -39,7 +39,9 @@ describe("FairExhibitors", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } diff --git a/src/lib/Scenes/Fair/FairFollowedArtistsRail.tests.tsx b/src/lib/Scenes/Fair/FairFollowedArtistsRail.tests.tsx index ba41e4f5a6b..3c13b49fb6b 100644 --- a/src/lib/Scenes/Fair/FairFollowedArtistsRail.tests.tsx +++ b/src/lib/Scenes/Fair/FairFollowedArtistsRail.tests.tsx @@ -23,7 +23,9 @@ describe("FairFollowedArtistsRail", () => { environment={env} query={graphql` - query FairFollowedArtistsRailTestsQuery($fairID: String!) @raw_response_type @relay_test_operation { + query FairFollowedArtistsRailTestsQuery($fairID: String!) + @raw_response_type + @relay_test_operation { fair(id: $fairID) { ...FairFollowedArtistsRail_fair } @@ -48,7 +50,9 @@ describe("FairFollowedArtistsRail", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Fair/FairHeader.tests.tsx b/src/lib/Scenes/Fair/FairHeader.tests.tsx index 716c304367f..67370200180 100644 --- a/src/lib/Scenes/Fair/FairHeader.tests.tsx +++ b/src/lib/Scenes/Fair/FairHeader.tests.tsx @@ -45,7 +45,9 @@ describe("FairHeader", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -61,7 +63,9 @@ describe("FairHeader", () => { name: "Art Basel Hong Kong 2020", }), }) - expect(wrapper.root.findByProps({ variant: "lg" }).props.children).toBe("Art Basel Hong Kong 2020") + expect(wrapper.root.findByProps({ variant: "lg" }).props.children).toBe( + "Art Basel Hong Kong 2020" + ) }) it("renders the fair main image when present", () => { diff --git a/src/lib/Scenes/Fair/FairMoreInfo.tests.tsx b/src/lib/Scenes/Fair/FairMoreInfo.tests.tsx index b513c971ef4..c1354ac7024 100644 --- a/src/lib/Scenes/Fair/FairMoreInfo.tests.tsx +++ b/src/lib/Scenes/Fair/FairMoreInfo.tests.tsx @@ -45,7 +45,9 @@ describe("FairMoreInfo", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } diff --git a/src/lib/Scenes/Fair/FairMoreInfo.tsx b/src/lib/Scenes/Fair/FairMoreInfo.tsx index 09ab9a007e4..eeaa91875b2 100644 --- a/src/lib/Scenes/Fair/FairMoreInfo.tsx +++ b/src/lib/Scenes/Fair/FairMoreInfo.tsx @@ -27,7 +27,9 @@ interface LocationCoordinates { lng: number | null } -export const shouldShowLocationMap = (coordinates: LocationCoordinates | null | undefined): boolean => { +export const shouldShowLocationMap = ( + coordinates: LocationCoordinates | null | undefined +): boolean => { return !!(coordinates && coordinates?.lat && coordinates?.lng) } @@ -76,7 +78,10 @@ export const FairMoreInfo: React.FC = ({ fair }) => { {!!shouldShowLocationMap(fair.location?.coordinates) && ( <> - + )} diff --git a/src/lib/Scenes/Favorites/FavoriteArtists.tsx b/src/lib/Scenes/Favorites/FavoriteArtists.tsx index a5679cda7e1..e9844ad2fe4 100644 --- a/src/lib/Scenes/Favorites/FavoriteArtists.tsx +++ b/src/lib/Scenes/Favorites/FavoriteArtists.tsx @@ -61,17 +61,28 @@ class Artists extends React.Component { // @TODO: Implement test on this component https://artsyproduct.atlassian.net/browse/LD-563 render() { - const rows = extractNodes(this.props.me.followsAndSaves?.artists, (node) => node.artist!).map((artist) => ({ - key: artist.id, - content: ( - - ), - })) + const rows = extractNodes(this.props.me.followsAndSaves?.artists, (node) => node.artist!).map( + (artist) => ({ + key: artist.id, + content: ( + + ), + }) + ) if (rows.length === 0) { return ( } + refreshControl={ + + } > { contentContainerStyle={{ paddingVertical: space(2) }} onEndReachedThreshold={0.2} refreshControl={ - + } style={{ paddingHorizontal: 0 }} ItemSeparatorComponent={() => } ListFooterComponent={ - this.state.fetchingMoreData ? : null + this.state.fetchingMoreData ? ( + + ) : null } /> )} @@ -112,7 +128,8 @@ const FavoriteArtistsContainer = createPaginationContainer( @argumentDefinitions(count: { type: "Int", defaultValue: 10 }, cursor: { type: "String" }) { labFeatures followsAndSaves { - artists: artistsConnection(first: $count, after: $cursor) @connection(key: "Artists_artists") { + artists: artistsConnection(first: $count, after: $cursor) + @connection(key: "Artists_artists") { edges { node { artist { diff --git a/src/lib/Scenes/Favorites/FavoriteArtworks.tsx b/src/lib/Scenes/Favorites/FavoriteArtworks.tsx index 5033c4e962d..fcfa32721eb 100644 --- a/src/lib/Scenes/Favorites/FavoriteArtworks.tsx +++ b/src/lib/Scenes/Favorites/FavoriteArtworks.tsx @@ -78,7 +78,10 @@ export class SavedWorks extends Component { {({ space }) => ( + } contentContainerStyle={{ paddingBottom: space(2) }} > @@ -110,7 +113,10 @@ export class SavedWorks extends Component { contentContainerStyle={{ paddingVertical: space(2) }} onEndReached={this.loadMore} refreshControl={ - + } > { // @TODO: Implement test on this component https://artsyproduct.atlassian.net/browse/LD-563 render() { - const rows = extractNodes(this.props.me.followsAndSaves?.genes, (node) => node.gene!).map((gene) => ({ - key: gene.id, - content: , - })) + const rows = extractNodes(this.props.me.followsAndSaves?.genes, (node) => node.gene!).map( + (gene) => ({ + key: gene.id, + content: ( + + ), + }) + ) if (rows.length === 0) { return ( } + refreshControl={ + + } > { ItemSeparatorComponent={() => } onEndReached={this.loadMore} onEndReachedThreshold={0.2} - refreshControl={} + refreshControl={ + + } ListFooterComponent={ - this.state.fetchingMoreData ? : null + this.state.fetchingMoreData ? ( + + ) : null } /> ) @@ -103,7 +119,8 @@ const FavoriteCategoriesContainer = createPaginationContainer( fragment FavoriteCategories_me on Me @argumentDefinitions(count: { type: "Int", defaultValue: 10 }, cursor: { type: "String" }) { followsAndSaves { - genes: genesConnection(first: $count, after: $cursor) @connection(key: "Categories_followed_genes") { + genes: genesConnection(first: $count, after: $cursor) + @connection(key: "Categories_followed_genes") { pageInfo { endCursor hasNextPage diff --git a/src/lib/Scenes/Favorites/FavoriteShows.tsx b/src/lib/Scenes/Favorites/FavoriteShows.tsx index b4689641d5d..c975fc36f7c 100644 --- a/src/lib/Scenes/Favorites/FavoriteShows.tsx +++ b/src/lib/Scenes/Favorites/FavoriteShows.tsx @@ -68,7 +68,12 @@ export class Shows extends Component { if (!shows.length) { return ( } + refreshControl={ + + } > { onEndReached={this.loadMore} onEndReachedThreshold={0.2} ItemSeparatorComponent={() => } - refreshControl={} + refreshControl={ + + } ListFooterComponent={ - this.state.fetchingMoreData ? : null + this.state.fetchingMoreData ? ( + + ) : null } /> ) @@ -102,7 +114,8 @@ const FavoriteShowsContainer = createPaginationContainer( fragment FavoriteShows_me on Me @argumentDefinitions(count: { type: "Int", defaultValue: 10 }, cursor: { type: "String" }) { followsAndSaves { - shows: showsConnection(first: $count, after: $cursor) @connection(key: "SavedShows_shows") { + shows: showsConnection(first: $count, after: $cursor) + @connection(key: "SavedShows_shows") { pageInfo { startCursor endCursor diff --git a/src/lib/Scenes/Favorites/Favorites.tsx b/src/lib/Scenes/Favorites/Favorites.tsx index 698cee8f6ed..097ba926b7f 100644 --- a/src/lib/Scenes/Favorites/Favorites.tsx +++ b/src/lib/Scenes/Favorites/Favorites.tsx @@ -101,7 +101,11 @@ export const Favorites: React.FC = ({ initialTab = Tab.works }) => { : <> + enableMyCollection ? ( + + ) : ( + <> + ) } stickyHeaderContent={ enableMyCollection ? ( @@ -122,7 +126,9 @@ export const Favorites: React.FC = ({ initialTab = Tab.works }) => { ) } /> - {!!isStaging && } + {!!isStaging && ( + + )} ) diff --git a/src/lib/Scenes/Feature/Feature.tests.tsx b/src/lib/Scenes/Feature/Feature.tests.tsx index d31abd9127b..1682bedcee5 100644 --- a/src/lib/Scenes/Feature/Feature.tests.tsx +++ b/src/lib/Scenes/Feature/Feature.tests.tsx @@ -11,7 +11,8 @@ jest.mock("lib/relay/createEnvironment", () => { }) let mockRelayEnvironment = defaultEnvironment as ReturnType beforeEach(() => { - mockRelayEnvironment = require("lib/relay/createEnvironment").defaultEnvironment = createMockEnvironment() + mockRelayEnvironment = require("lib/relay/createEnvironment").defaultEnvironment = + createMockEnvironment() }) describe(FeatureQueryRenderer, () => { diff --git a/src/lib/Scenes/Feature/Feature.tsx b/src/lib/Scenes/Feature/Feature.tsx index be19d351f05..4816bfbb0ea 100644 --- a/src/lib/Scenes/Feature/Feature.tsx +++ b/src/lib/Scenes/Feature/Feature.tsx @@ -14,7 +14,10 @@ import { Flex, Sans, Separator, Spacer } from "palette" import React from "react" import { createFragmentContainer, graphql, QueryRenderer } from "react-relay" import { FeatureFeaturedLinkFragmentContainer } from "./components/FeatureFeaturedLink" -import { FeatureHeaderFragmentContainer, FeatureHeaderPlaceholder } from "./components/FeatureHeader" +import { + FeatureHeaderFragmentContainer, + FeatureHeaderPlaceholder, +} from "./components/FeatureHeader" import { FeatureMarkdown } from "./components/FeatureMarkdown" const SUPPORTED_ITEM_TYPES = ["FeaturedLink", "Artwork"] @@ -26,7 +29,11 @@ interface FlatListSection { type FlatListSections = Array -function addSeparatorBetweenAllSections(sections: FlatListSections, key: string, element: JSX.Element) { +function addSeparatorBetweenAllSections( + sections: FlatListSections, + key: string, + element: JSX.Element +) { const result: FlatListSections = [] for (let i = 0; i < sections.length; i++) { result.push(sections[i]) @@ -48,7 +55,10 @@ const FeatureApp: React.FC = ({ feature }) => { const sets = extractNodes(feature.sets) const { width, orientation } = useScreenDimensions() - const header: FlatListSection = { key: "header", content: } + const header: FlatListSection = { + key: "header", + content: , + } // these are the major sections of the page which get separated by a black line const contentSections: FlatListSections = [] @@ -59,8 +69,12 @@ const FeatureApp: React.FC = ({ feature }) => { content: ( - {!!feature.description && } - {!!feature.callout && } + {!!feature.description && ( + + )} + {!!feature.callout && ( + + )} ), @@ -113,7 +127,11 @@ const FeatureApp: React.FC = ({ feature }) => { {row.map((item) => { return ( - + ) })} @@ -121,7 +139,13 @@ const FeatureApp: React.FC = ({ feature }) => { }) } - renderedSet.push(addSeparatorBetweenAllSections(renderedRows, set.id + ":featuredLink", )) + renderedSet.push( + addSeparatorBetweenAllSections( + renderedRows, + set.id + ":featuredLink", + + ) + ) break case "Artwork": diff --git a/src/lib/Scenes/Feature/components/FeatureFeaturedLink.tsx b/src/lib/Scenes/Feature/components/FeatureFeaturedLink.tsx index 37c715c09d9..e84b46ded12 100644 --- a/src/lib/Scenes/Feature/components/FeatureFeaturedLink.tsx +++ b/src/lib/Scenes/Feature/components/FeatureFeaturedLink.tsx @@ -26,7 +26,11 @@ const FeatureFeaturedLink: React.FC = ({ featuredLink, : undefined } > - + = ({ feature }) => { const imageHeight = isPad() ? height * 0.6 : width const imageWidth = isPad() ? width / 2 : width - const image = + const image = ( + + ) const title = ( {feature.name} diff --git a/src/lib/Scenes/Feature/components/FeatureMarkdown.tsx b/src/lib/Scenes/Feature/components/FeatureMarkdown.tsx index d3139200714..4a83b54f145 100644 --- a/src/lib/Scenes/Feature/components/FeatureMarkdown.tsx +++ b/src/lib/Scenes/Feature/components/FeatureMarkdown.tsx @@ -4,10 +4,10 @@ import React from "react" import { Text } from "react-native" import SimpleMarkdown from "simple-markdown" -export const FeatureMarkdown: React.FC<{ content: string; sansProps?: Partial> }> = ({ - content, - sansProps, -}) => { +export const FeatureMarkdown: React.FC<{ + content: string + sansProps?: Partial> +}> = ({ content, sansProps }) => { const rendered = renderMarkdown(content, { ...defaultRules({ modal: false, @@ -28,7 +28,11 @@ export const FeatureMarkdown: React.FC<{ content: string; sansProps?: Partial = ({ forceUpdateMessage }) {forceUpdateMessage} - diff --git a/src/lib/Scenes/Gene/Gene.tests.tsx b/src/lib/Scenes/Gene/Gene.tests.tsx index 7f027444486..91e58433184 100644 --- a/src/lib/Scenes/Gene/Gene.tests.tsx +++ b/src/lib/Scenes/Gene/Gene.tests.tsx @@ -26,7 +26,8 @@ describe("Gene", () => { environment={environment} query={graphql` - query GeneTestsQuery($geneID: String!, $input: FilterArtworksInput) @relay_test_operation { + query GeneTestsQuery($geneID: String!, $input: FilterArtworksInput) + @relay_test_operation { gene(id: $geneID) { slug ...Header_gene diff --git a/src/lib/Scenes/Home/Components/ArticlesRail.tsx b/src/lib/Scenes/Home/Components/ArticlesRail.tsx index 91274d7e362..589c0c42e7a 100644 --- a/src/lib/Scenes/Home/Components/ArticlesRail.tsx +++ b/src/lib/Scenes/Home/Components/ArticlesRail.tsx @@ -48,7 +48,11 @@ export const ArticlesRail: React.FC = ({ title, articlesConne renderItem={({ item, index }) => ( { - const tapEvent = HomeAnalytics.articleThumbnailTapEvent(item.internalID, item.slug || "", index) + const tapEvent = HomeAnalytics.articleThumbnailTapEvent( + item.internalID, + item.slug || "", + index + ) tracking.trackEvent(tapEvent) }} article={item} diff --git a/src/lib/Scenes/Home/Components/ArtworkModuleRail.tsx b/src/lib/Scenes/Home/Components/ArtworkModuleRail.tsx index d29cf76e336..a5472dee8bc 100644 --- a/src/lib/Scenes/Home/Components/ArtworkModuleRail.tsx +++ b/src/lib/Scenes/Home/Components/ArtworkModuleRail.tsx @@ -37,7 +37,12 @@ interface ArtworkModuleRailProps { mb?: number } -const ArtworkModuleRail: React.FC = ({ title, rail, scrollRef, mb }) => { +const ArtworkModuleRail: React.FC = ({ + title, + rail, + scrollRef, + mb, +}) => { const tracking = useTracking() const railRef = useRef(null) const listRef = useRef>(null) @@ -90,7 +95,14 @@ const ArtworkModuleRail: React.FC = ({ artworks={artworks} onPress={(artwork, position) => { if (contextModule) { - tracking.trackEvent(HomeAnalytics.artworkThumbnailTapEvent(contextModule, artwork.slug, position, "single")) + tracking.trackEvent( + HomeAnalytics.artworkThumbnailTapEvent( + contextModule, + artwork.slug, + position, + "single" + ) + ) } navigate(artwork.href!) diff --git a/src/lib/Scenes/Home/Components/CollectionsRail.tests.tsx b/src/lib/Scenes/Home/Components/CollectionsRail.tests.tsx index 7718b6821be..b4fcee828a7 100644 --- a/src/lib/Scenes/Home/Components/CollectionsRail.tests.tsx +++ b/src/lib/Scenes/Home/Components/CollectionsRail.tests.tsx @@ -117,7 +117,9 @@ describe("CollectionsRailFragmentContainer", () => { }) // @ts-ignore first(tree.root.findAllByType(CardRailCard)).props.onPress() - expect(mockTrackEvent).toHaveBeenCalledWith(HomeAnalytics.collectionThumbnailTapEvent("test-collection-one", 0)) + expect(mockTrackEvent).toHaveBeenCalledWith( + HomeAnalytics.collectionThumbnailTapEvent("test-collection-one", 0) + ) }) }) diff --git a/src/lib/Scenes/Home/Components/CollectionsRail.tsx b/src/lib/Scenes/Home/Components/CollectionsRail.tsx index 4cd91c94f11..9745e1fd360 100644 --- a/src/lib/Scenes/Home/Components/CollectionsRail.tsx +++ b/src/lib/Scenes/Home/Components/CollectionsRail.tsx @@ -55,14 +55,20 @@ const CollectionsRail: React.FC = (props) => { renderItem={({ item: result, index }) => { // Collections are expected to always have >= 2 artworks, but we should // still be cautious to avoid crashes if this assumption is broken. - const artworkImageURLs = extractNodes(result.artworksConnection, (artwork) => artwork.image?.url!) + const artworkImageURLs = extractNodes( + result.artworksConnection, + (artwork) => artwork.image?.url! + ) return ( { - const tapEvent = HomeAnalytics.collectionThumbnailTapEvent(result?.slug, index) + const tapEvent = HomeAnalytics.collectionThumbnailTapEvent( + result?.slug, + index + ) if (tapEvent) { tracking.trackEvent(tapEvent) } @@ -73,7 +79,11 @@ const CollectionsRail: React.FC = (props) => { > - + = (props) => { {result?.title} - {result?.artworksConnection?.counts?.total ? `${result.artworksConnection.counts.total} works` : ""} + {result?.artworksConnection?.counts?.total + ? `${result.artworksConnection.counts.total} works` + : ""} diff --git a/src/lib/Scenes/Home/Components/EmailConfirmationBanner.tsx b/src/lib/Scenes/Home/Components/EmailConfirmationBanner.tsx index b5d4e84af21..0a598cc9583 100644 --- a/src/lib/Scenes/Home/Components/EmailConfirmationBanner.tsx +++ b/src/lib/Scenes/Home/Components/EmailConfirmationBanner.tsx @@ -103,7 +103,12 @@ export const EmailConfirmationBanner: React.FC = ({ me, relay }) => { ) : ( - + {message} toggleVisible(false)}> @@ -119,10 +124,13 @@ export const EmailConfirmationBanner: React.FC = ({ me, relay }) => { } } -export const EmailConfirmationBannerFragmentContainer = createFragmentContainer(EmailConfirmationBanner, { - me: graphql` - fragment EmailConfirmationBanner_me on Me { - canRequestEmailConfirmation - } - `, -}) +export const EmailConfirmationBannerFragmentContainer = createFragmentContainer( + EmailConfirmationBanner, + { + me: graphql` + fragment EmailConfirmationBanner_me on Me { + canRequestEmailConfirmation + } + `, + } +) diff --git a/src/lib/Scenes/Home/Components/FairsRail.tests.tsx b/src/lib/Scenes/Home/Components/FairsRail.tests.tsx index 896664fe8f5..b770d0dddd0 100644 --- a/src/lib/Scenes/Home/Components/FairsRail.tests.tsx +++ b/src/lib/Scenes/Home/Components/FairsRail.tests.tsx @@ -69,20 +69,32 @@ const fairsModule: Omit = { it("renders without throwing an error", () => { renderWithWrappers( - + ) }) it("renders results when there are fairs returned", () => { const tree = renderWithWrappers( - + ) expect(tree.root.findAllByType(Text)[0].props.children).toMatch("Featured Fairs") }) it("does not render results when there are no fairs returned", () => { const tree = renderWithWrappers( - + ) expect(tree.root.findAllByType(SectionTitle).length).toEqual(0) }) @@ -97,7 +109,11 @@ it("renders without throwing an error when missing artworks", () => { }) expect(() => renderWithWrappers( - + ) ).not.toThrow() }) @@ -108,11 +124,15 @@ describe("location", () => { // @ts-ignore fairsCopy.results[0].location.city = "New Yawk" const tree = renderWithWrappers( - - ) - expect(extractText(tree.root.findAllByProps({ testID: "card-subtitle" })[0])).toMatchInlineSnapshot( - `"Monday–Friday • New Yawk"` + ) + expect( + extractText(tree.root.findAllByProps({ testID: "card-subtitle" })[0]) + ).toMatchInlineSnapshot(`"Monday–Friday • New Yawk"`) }) it("handles falls back to country when city is unspecified", () => { @@ -120,18 +140,26 @@ describe("location", () => { // @ts-ignore fairsCopy.results[0].location.country = "Canada" const tree = renderWithWrappers( - - ) - expect(extractText(tree.root.findAllByProps({ testID: "card-subtitle" })[0])).toMatchInlineSnapshot( - `"Monday–Friday • Canada"` + ) + expect( + extractText(tree.root.findAllByProps({ testID: "card-subtitle" })[0]) + ).toMatchInlineSnapshot(`"Monday–Friday • Canada"`) }) }) describe("navigation", () => { it("navigates to the fair url", () => { const tree = renderWithWrappers( - + ) const cards = tree.root.findAllByType(CardRailCard) cards[0].props.onPress() @@ -143,7 +171,11 @@ describe("analytics", () => { it("tracks fair thumbnail taps", () => { const fairsCopy = cloneDeep(fairsModule) const tree = renderWithWrappers( - + ) const cards = tree.root.findAllByType(CardRailCard) cards[0].props.onPress() diff --git a/src/lib/Scenes/Home/Components/FairsRail.tsx b/src/lib/Scenes/Home/Components/FairsRail.tsx index bc71bca9edf..26fb2aac860 100644 --- a/src/lib/Scenes/Home/Components/FairsRail.tsx +++ b/src/lib/Scenes/Home/Components/FairsRail.tsx @@ -72,7 +72,9 @@ const FairsRail: React.FC = (props) => { { - tracking.trackEvent(HomeAnalytics.fairThumbnailTapEvent(result?.internalID, result?.slug, index)) + tracking.trackEvent( + HomeAnalytics.fairThumbnailTapEvent(result?.internalID, result?.slug, index) + ) if (result?.slug) { navigate(`/fair/${result?.slug}`) } @@ -80,7 +82,11 @@ const FairsRail: React.FC = (props) => { > - + { } } `} - render={({ props }) => (props?.homePage ? : null)} + render={({ props }) => + props?.homePage ? : null + } variables={{}} environment={environment} /> @@ -49,7 +51,9 @@ describe("HomeHero", () => { ) expect(tree.root.findAllByType(OpaqueImageView)).toHaveLength(1) - expect(extractText(tree.root)).toMatchInlineSnapshot(`"Art Keeps GoingArt in the time of pandemicLearn More"`) + expect(extractText(tree.root)).toMatchInlineSnapshot( + `"Art Keeps GoingArt in the time of pandemicLearn More"` + ) }) it(`only shows the credit line after the image has loaded`, () => { diff --git a/src/lib/Scenes/Home/Components/NewWorksForYouRail.tsx b/src/lib/Scenes/Home/Components/NewWorksForYouRail.tsx index 0c709253ec1..aa60bdb7774 100644 --- a/src/lib/Scenes/Home/Components/NewWorksForYouRail.tsx +++ b/src/lib/Scenes/Home/Components/NewWorksForYouRail.tsx @@ -26,7 +26,10 @@ export const NewWorksForYouRail: React.FC { const { trackEvent } = useTracking() - const { newWorksByInterestingArtists } = useFragment(artworksFragment, me) + const { newWorksByInterestingArtists } = useFragment( + artworksFragment, + me + ) const railRef = useRef(null) const listRef = useRef>(null) @@ -57,7 +60,12 @@ export const NewWorksForYouRail: React.FC { trackEvent( - HomeAnalytics.artworkThumbnailTapEvent(ContextModule.newWorksForYouRail, artwork.slug, position, "single") + HomeAnalytics.artworkThumbnailTapEvent( + ContextModule.newWorksForYouRail, + artwork.slug, + position, + "single" + ) ) navigate(artwork.href!) }} diff --git a/src/lib/Scenes/Home/Components/SalesRail.tests.tsx b/src/lib/Scenes/Home/Components/SalesRail.tests.tsx index a69373821de..9b4814eb0c3 100644 --- a/src/lib/Scenes/Home/Components/SalesRail.tests.tsx +++ b/src/lib/Scenes/Home/Components/SalesRail.tests.tsx @@ -56,7 +56,11 @@ const salesModule: Omit = { it("doesn't throw when rendered", () => { expect(() => renderWithWrappers( - + ) ).not.toThrow() }) @@ -69,7 +73,11 @@ it("looks correct when rendered with sales missing artworks", () => { }) expect(() => renderWithWrappers( - + ) ).not.toThrow() }) @@ -81,7 +89,11 @@ describe("image handling", () => { // @ts-ignore sale!.saleArtworksConnection!.edges = edges return renderWithWrappers( - + ) } @@ -111,7 +123,9 @@ describe("image handling", () => { }) it("renders the 1st as a fallback if the 2nd and 3rd are missing", () => { - const tree = render([{ node: { artwork: { image: { url: "https://example.com/image-1.jpg" } } } }]) + const tree = render([ + { node: { artwork: { image: { url: "https://example.com/image-1.jpg" } } } }, + ]) expect(tree.root.findAllByType(ImageView).map(({ props }) => props.imageURL)).toEqual([ "https://example.com/image-1.jpg", "https://example.com/image-1.jpg", @@ -122,7 +136,11 @@ describe("image handling", () => { it("renders the correct subtitle based on auction type", async () => { const tree = renderWithWrappers( - + ) const subtitles = tree.root.findAllByProps({ testID: "sale-subtitle" }) // Timed sale @@ -135,7 +153,11 @@ it("renders the correct subtitle based on auction type", async () => { it("routes to live URL if present, otherwise href", () => { const tree = renderWithWrappers( - + ) // Timed sale // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 @@ -150,7 +172,11 @@ it("routes to live URL if present, otherwise href", () => { describe("analytics", () => { it("tracks auction header taps", () => { const tree = renderWithWrappers( - + ) tree.root.findByType(SectionTitle as any).props.onPress() expect(mockTrackEvent).toHaveBeenCalledWith(HomeAnalytics.auctionHeaderTapEvent()) @@ -158,7 +184,11 @@ describe("analytics", () => { it("tracks auction thumbnail taps", () => { const tree = renderWithWrappers( - + ) const cards = tree.root.findAllByType(CardRailCard) cards[0].props.onPress() diff --git a/src/lib/Scenes/Home/Components/SalesRail.tsx b/src/lib/Scenes/Home/Components/SalesRail.tsx index d569f0e14d3..1b7af3bb0ab 100644 --- a/src/lib/Scenes/Home/Components/SalesRail.tsx +++ b/src/lib/Scenes/Home/Components/SalesRail.tsx @@ -30,11 +30,20 @@ interface Props { type Sale = SalesRail_salesModule["results"][0] -const SalesRail: React.FC = ({ title, subtitle, scrollRef, salesModule, mb }) => { +const SalesRail: React.FC = ({ + title, + subtitle, + scrollRef, + salesModule, + mb, +}) => { const listRef = useRef>() const tracking = useTracking() - const getSaleSubtitle = (liveStartAt: string | undefined | null, displayTimelyAt: string | undefined | null) => { + const getSaleSubtitle = ( + liveStartAt: string | undefined | null, + displayTimelyAt: string | undefined | null + ) => { const saleSubtitle = !!liveStartAt ? "Live Auction" : "Timed Auction" const dateAt = formatDisplayTimelyAt(displayTimelyAt !== undefined ? displayTimelyAt : null) if (dateAt) { @@ -87,7 +96,9 @@ const SalesRail: React.FC = ({ title, subtitle, scrollR { - tracking.trackEvent(HomeAnalytics.auctionThumbnailTapEvent(result?.internalID, result?.slug, index)) + tracking.trackEvent( + HomeAnalytics.auctionThumbnailTapEvent(result?.internalID, result?.slug, index) + ) const url = result?.liveURLIfOpen ?? result?.href if (url) { navigate(url) @@ -96,7 +107,11 @@ const SalesRail: React.FC = ({ title, subtitle, scrollR > - + { variables={{}} render={({ props, error }) => { if (props) { - return + return ( + + ) } else if (error) { console.log(error) } diff --git a/src/lib/Scenes/Home/Components/SmallTileRail.tsx b/src/lib/Scenes/Home/Components/SmallTileRail.tsx index ed78fd68ca4..97d85161aba 100644 --- a/src/lib/Scenes/Home/Components/SmallTileRail.tsx +++ b/src/lib/Scenes/Home/Components/SmallTileRail.tsx @@ -52,7 +52,12 @@ const SmallTileRail: React.FC = ({ ? () => { if (contextModule) { tracking.trackEvent( - HomeAnalytics.artworkThumbnailTapEvent(contextModule, item.slug, index, "single") + HomeAnalytics.artworkThumbnailTapEvent( + contextModule, + item.slug, + index, + "single" + ) ) } navigate(item.href!) @@ -64,7 +69,9 @@ const SmallTileRail: React.FC = ({ useSquareAspectRatio artistNames={item.artistNames} saleMessage={saleMessageOrBidInfo({ artwork: item, isSmallTile: true })} - urgencyTag={item?.sale?.isAuction && !item?.sale?.isClosed ? getUrgencyTag(item?.sale?.endAt) : null} + urgencyTag={ + item?.sale?.isAuction && !item?.sale?.isClosed ? getUrgencyTag(item?.sale?.endAt) : null + } /> )} keyExtractor={(item, index) => String(item.image?.imageURL || index)} diff --git a/src/lib/Scenes/Home/Components/Trove.tests.tsx b/src/lib/Scenes/Home/Components/Trove.tests.tsx index e1bc08f4981..63f671f3764 100644 --- a/src/lib/Scenes/Home/Components/Trove.tests.tsx +++ b/src/lib/Scenes/Home/Components/Trove.tests.tsx @@ -27,7 +27,9 @@ describe("Trove", () => { } } `} - render={({ props }) => (props?.homePage ? : null)} + render={({ props }) => + props?.homePage ? : null + } variables={{}} environment={environment} /> @@ -48,7 +50,9 @@ describe("Trove", () => { ) expect(tree.root.findAllByType(OpaqueImageView)).toHaveLength(1) - expect(extractText(tree.root)).toMatchInlineSnapshot(`"TroveBrowse available artworks by emerging artists."`) + expect(extractText(tree.root)).toMatchInlineSnapshot( + `"TroveBrowse available artworks by emerging artists."` + ) }) it("is tappable", () => { diff --git a/src/lib/Scenes/Home/Components/Trove.tsx b/src/lib/Scenes/Home/Components/Trove.tsx index 7bec4028665..6fd0066c07c 100644 --- a/src/lib/Scenes/Home/Components/Trove.tsx +++ b/src/lib/Scenes/Home/Components/Trove.tsx @@ -33,7 +33,8 @@ const Trove: React.FC = ({ trove, mb }) => { export const TroveFragmentContainer = createFragmentContainer(Trove, { trove: graphql` - fragment Trove_trove on HomePage @argumentDefinitions(heroImageVersion: { type: "HomePageHeroUnitImageVersion" }) { + fragment Trove_trove on HomePage + @argumentDefinitions(heroImageVersion: { type: "HomePageHeroUnitImageVersion" }) { heroUnits(platform: MOBILE) { title subtitle diff --git a/src/lib/Scenes/Home/Home.tsx b/src/lib/Scenes/Home/Home.tsx index 855d33b5810..e36166f4962 100644 --- a/src/lib/Scenes/Home/Home.tsx +++ b/src/lib/Scenes/Home/Home.tsx @@ -92,7 +92,9 @@ const Home = (props: Props) => { relay, } = props - const enableAuctionResultsByFollowedArtists = useFeatureFlag("ARHomeAuctionResultsByFollowedArtists") + const enableAuctionResultsByFollowedArtists = useFeatureFlag( + "ARHomeAuctionResultsByFollowedArtists" + ) const enableViewingRooms = useFeatureFlag("AREnableViewingRooms") const enableTrove = useFeatureFlag("AREnableTrove") const enableShowsForYouRail = useFeatureFlag("AREnableShowsRail") @@ -191,7 +193,11 @@ const Home = (props: Props) => { data: homePageBelow?.fairsModule, }, { title: "Popular Artists", type: "artist", data: homePageBelow?.popularArtistsArtistModule }, - { title: "Recently Viewed", type: "artwork", data: homePageBelow?.recentlyViewedWorksArtworkModule }, + { + title: "Recently Viewed", + type: "artwork", + data: homePageBelow?.recentlyViewedWorksArtworkModule, + }, { title: "Similar to Works You've Viewed", type: "artwork", @@ -251,7 +257,11 @@ const Home = (props: Props) => { ) case "auction-results": return ( - + ) case "collections": return ( @@ -274,7 +284,11 @@ const Home = (props: Props) => { ) case "lotsByFollowedArtists": return ( - + ) case "newWorksForYou": return ( @@ -315,7 +329,13 @@ const Home = (props: Props) => { case "trove": return case "viewing-rooms": - return + return ( + + ) default: return null } @@ -597,7 +617,9 @@ const messages = { } export const HomeQueryRenderer: React.FC = () => { - const { flash_message } = GlobalStore.useAppState((state) => state.bottomTabs.sessionState.tabProps.home ?? {}) as { + const { flash_message } = GlobalStore.useAppState( + (state) => state.bottomTabs.sessionState.tabProps.home ?? {} + ) as { flash_message?: string } @@ -630,7 +652,8 @@ export const HomeQueryRenderer: React.FC = () => { ...Home_meAbove ...NewWorksForYouRail_me } - articlesConnection(first: 10, sort: PUBLISHED_AT_DESC, inEditorialFeed: true) @optionalField { + articlesConnection(first: 10, sort: PUBLISHED_AT_DESC, inEditorialFeed: true) + @optionalField { ...Home_articlesConnection } } diff --git a/src/lib/Scenes/Home/TabBar.tests.tsx b/src/lib/Scenes/Home/TabBar.tests.tsx index 656a0d5fac0..321a2e5b31c 100644 --- a/src/lib/Scenes/Home/TabBar.tests.tsx +++ b/src/lib/Scenes/Home/TabBar.tests.tsx @@ -5,5 +5,7 @@ import { Animated } from "react-native" import TabBar from "lib/Components/TabBar" it("renders without throwing an error", () => { - renderWithWrappers() + renderWithWrappers( + + ) }) diff --git a/src/lib/Scenes/Home/homeAnalytics.tests.ts b/src/lib/Scenes/Home/homeAnalytics.tests.ts index ec76baf7bda..583b0866361 100644 --- a/src/lib/Scenes/Home/homeAnalytics.tests.ts +++ b/src/lib/Scenes/Home/homeAnalytics.tests.ts @@ -52,7 +52,10 @@ describe("Events", () => { type: "header", }) - const thumbnailTapEvent = HomeAnalytics.artworkThumbnailTapEventFromKey(artworkRail.key, "some-slug") + const thumbnailTapEvent = HomeAnalytics.artworkThumbnailTapEventFromKey( + artworkRail.key, + "some-slug" + ) expect(thumbnailTapEvent).toEqual({ action: Analytics.ActionType.tappedArtworkGroup, context_module: Analytics.ContextModule.newWorksByArtistsYouFollowRail, @@ -65,7 +68,11 @@ describe("Events", () => { }) it("returns correct artist events", () => { - const artistThumbnailTapEvent = HomeAnalytics.artistThumbnailTapEvent("SUGGESTED", "artist-id", "artist-slug") + const artistThumbnailTapEvent = HomeAnalytics.artistThumbnailTapEvent( + "SUGGESTED", + "artist-id", + "artist-slug" + ) expect(artistThumbnailTapEvent).toEqual({ action: Analytics.ActionType.tappedArtistGroup, context_module: Analytics.ContextModule.recommendedArtistsRail, @@ -79,7 +86,11 @@ describe("Events", () => { }) it("returns correct articles events", () => { - const artistThumbnailTapEvent = HomeAnalytics.articleThumbnailTapEvent("article-id", "article-slug", 1) + const artistThumbnailTapEvent = HomeAnalytics.articleThumbnailTapEvent( + "article-id", + "article-slug", + 1 + ) expect(artistThumbnailTapEvent).toEqual({ action: Analytics.ActionType.tappedArticleGroup, context_module: Analytics.ContextModule.articleRail, diff --git a/src/lib/Scenes/Home/homeAnalytics.ts b/src/lib/Scenes/Home/homeAnalytics.ts index 15eefb70fa9..2c9073a829c 100644 --- a/src/lib/Scenes/Home/homeAnalytics.ts +++ b/src/lib/Scenes/Home/homeAnalytics.ts @@ -43,7 +43,11 @@ export default class HomeAnalytics { // Fair events - static fairThumbnailTapEvent(fairID?: string, fairSlug?: string, index?: number): Analytics.TappedEntityGroup { + static fairThumbnailTapEvent( + fairID?: string, + fairSlug?: string, + index?: number + ): Analytics.TappedEntityGroup { return Analytics.tappedEntityGroup({ contextScreenOwnerType: Analytics.OwnerType.home, destinationScreenOwnerId: fairID, diff --git a/src/lib/Scenes/Inbox/Components/ActiveBids/ActiveBid.tsx b/src/lib/Scenes/Inbox/Components/ActiveBids/ActiveBid.tsx index 312dc6ca900..8e673d79585 100644 --- a/src/lib/Scenes/Inbox/Components/ActiveBids/ActiveBid.tsx +++ b/src/lib/Scenes/Inbox/Components/ActiveBids/ActiveBid.tsx @@ -113,16 +113,25 @@ class ActiveBid extends React.Component { handleTap = () => { const bid = this.props.bid // push user into live auction if it's open; otherwise go to artwork - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const href = this.state.status === "live_auction" ? bid.sale.href : bid.most_recent_bid.sale_artwork.artwork.href + const href = + this.state.status === "live_auction" + ? // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + bid.sale.href + : // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + bid.most_recent_bid.sale_artwork.artwork.href // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 navigate(href) } render() { const bid = this.props.bid.most_recent_bid - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const imageURL = bid.sale_artwork.artwork && bid.sale_artwork.artwork.image && bid.sale_artwork.artwork.image.url + const imageURL = + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + bid.sale_artwork.artwork && + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + bid.sale_artwork.artwork.image && + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + bid.sale_artwork.artwork.image.url // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 const lotNumber = bid.sale_artwork.lot_label // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Composer.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Composer.tests.tsx index 359000706ce..222209e471e 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Composer.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Composer.tests.tsx @@ -39,7 +39,9 @@ const TestRenderer = (nonRelayProps: { disabled: boolean; value?: string }) => ( variables={{}} render={({ props, error }) => { if (Boolean(props?.me?.conversation)) { - return + return ( + + ) } else if (Boolean(error)) { console.log(error) } @@ -51,7 +53,9 @@ const defaultProps = { disabled: false } const getWrapper = (mockResolvers = {}, nonRelayProps = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Composer.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Composer.tsx index 14da56cecb3..c27d8b4024a 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Composer.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Composer.tsx @@ -92,7 +92,10 @@ export default class Composer extends React.Component { {this.props.children} - + { multiline value={this.state.text || undefined} /> - + diff --git a/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tests.tsx index bd5718f1bc6..c1687eca0c1 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tests.tsx @@ -34,7 +34,9 @@ describe("ConversationCTA", () => { variables={{ conversationID: "test-conversation" }} render={({ error, props }) => { if (props?.me?.conversation) { - return + return ( + + ) } else if (error) { console.error(error) } @@ -69,7 +71,9 @@ describe("ConversationCTA", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -121,7 +125,10 @@ describe("ConversationCTA", () => { expectReviewOfferButton(wrapper, { bg: "red100", Icon: AlertCircleFillIcon, - strings: ["Payment Failed", "Unable to process payment for accepted offer. Update payment method."], + strings: [ + "Payment Failed", + "Unable to process payment for accepted offer. Update payment method.", + ], }) }) @@ -143,7 +150,11 @@ describe("ConversationCTA", () => { offerAmountChanged: true, }, }) - expectReviewOfferButton(wrapper, { bg: "copper100", strings: ["Offer Received"], Icon: AlertCircleFillIcon }) + expectReviewOfferButton(wrapper, { + bg: "copper100", + strings: ["Offer Received"], + Icon: AlertCircleFillIcon, + }) }) it("shows correct message for an offer accepted by the buyer", () => { @@ -152,7 +163,11 @@ describe("ConversationCTA", () => { lastOffer: { fromParticipant: "BUYER" }, }) - expectReviewOfferButton(wrapper, { bg: "green100", strings: ["Offer Accepted"], Icon: MoneyFillIcon }) + expectReviewOfferButton(wrapper, { + bg: "green100", + strings: ["Offer Accepted"], + Icon: MoneyFillIcon, + }) }) it("shows correct message for an offer accepted by the seller that does not define total (change amount)", () => { @@ -161,7 +176,11 @@ describe("ConversationCTA", () => { lastOffer: { fromParticipant: "SELLER", definesTotal: false }, }) - expectReviewOfferButton(wrapper, { bg: "green100", strings: ["Offer Accepted"], Icon: MoneyFillIcon }) + expectReviewOfferButton(wrapper, { + bg: "green100", + strings: ["Offer Accepted"], + Icon: MoneyFillIcon, + }) }) it("shows counter received - confirm total when offer defines total and amount changes", () => { @@ -183,7 +202,11 @@ describe("ConversationCTA", () => { lastOffer: { fromParticipant: "BUYER" }, }) - expectReviewOfferButton(wrapper, { bg: "green100", strings: ["Offer Accepted"], Icon: MoneyFillIcon }) + expectReviewOfferButton(wrapper, { + bg: "green100", + strings: ["Offer Accepted"], + Icon: MoneyFillIcon, + }) }) it("shows accepted - confirm total when offer defines total and amount stays the same", () => { diff --git a/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tsx b/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tsx index baecda2a400..1931390d27d 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/ConversationCTA.tsx @@ -57,10 +57,13 @@ export const ConversationCTA: React.FC = ({ conversation, show }) => { } else if (state === "FULFILLED") { kind = "OFFER_ACCEPTED" } else if (state === "APPROVED") { - const isProvisionalOffer = lastOffer?.fromParticipant === "SELLER" && lastOffer?.definesTotal + const isProvisionalOffer = + lastOffer?.fromParticipant === "SELLER" && lastOffer?.definesTotal kind = isProvisionalOffer ? "PROVISIONAL_OFFER_ACCEPTED" : "OFFER_ACCEPTED" } - CTA = kind && + CTA = kind && ( + + ) } } if (!CTA) { diff --git a/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tests.tsx index 669a08e4a20..eac12d32166 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tests.tsx @@ -6,11 +6,15 @@ import "react-native" import ConversationSnippet from "./ConversationSnippet" it("renders with an artwork without throwing an error", () => { - renderWithWrappers() + renderWithWrappers( + + ) }) it("renders with a show without throwing an error", () => { - renderWithWrappers() + renderWithWrappers( + + ) }) const artwork = { diff --git a/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tsx b/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tsx index faa932e3afd..2e0f404182d 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/ConversationSnippet.tsx @@ -85,7 +85,8 @@ export class ConversationSnippet extends React.Component { const partnerName = conversation.to.name - const conversationText = conversation.lastMessage && conversation.lastMessage.replace(/\n/g, " ") + const conversationText = + conversation.lastMessage && conversation.lastMessage.replace(/\n/g, " ") const date = moment(conversation.lastMessageAt).fromNow(true) + " ago" return ( diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tests.tsx index 8a61e0bbcfe..03b2fb55ea3 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tests.tsx @@ -40,7 +40,9 @@ describe("messaging inbox", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tsx index cfb216b2729..da233395c47 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Conversations.tsx @@ -27,7 +27,9 @@ interface Props { isActiveTab: boolean } -type Item = NonNullable["edges"]>[0]>["node"] +type Item = NonNullable< + NonNullable["edges"]>[0] +>["node"] // @track() export const Conversations: React.FC = (props) => { @@ -97,10 +99,17 @@ export const Conversations: React.FC = (props) => { const shouldDisplayMyBids = unsafe_getFeatureFlag("AROptionsBidManagement") return ( - + {!shouldDisplayMyBids && ( - + Inbox {unreadCounter} @@ -118,11 +127,19 @@ export const Conversations: React.FC = (props) => { keyExtractor={(item) => item.internalID!} ItemSeparatorComponent={() => } renderItem={({ item }) => { - return handleSelectConversation(item)} /> + return ( + handleSelectConversation(item)} + /> + ) }} onEndReached={fetchData} onEndReachedThreshold={0.2} - contentContainerStyle={{ flexGrow: 1, justifyContent: !conversations.length ? "center" : "flex-start" }} + contentContainerStyle={{ + flexGrow: 1, + justifyContent: !conversations.length ? "center" : "flex-start", + }} ListEmptyComponent={} /> {!!(relay.hasMore() && isLoading) && ( @@ -155,7 +172,10 @@ export const ConversationsContainer = createPaginationContainer( { me: graphql` fragment Conversations_me on Me - @argumentDefinitions(count: { type: "Int", defaultValue: 10 }, cursor: { type: "String", defaultValue: "" }) { + @argumentDefinitions( + count: { type: "Int", defaultValue: 10 } + cursor: { type: "String", defaultValue: "" } + ) { conversations: conversationsConnection(first: $count, after: $cursor) @connection(key: "Conversations_conversations") { pageInfo { diff --git a/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tests.tsx index 09fd620c10b..9cf9580b8ae 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tests.tsx @@ -57,7 +57,9 @@ const TestRenderer = () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tsx b/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tsx index 0023088342f..5b275545656 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tsx @@ -32,18 +32,22 @@ export class InquiryMakeOfferButton extends React.Component { - this.handleCreateInquiryOfferOrder() + Alert.alert( + "Sorry, we couldn't process the request.", + "Please try again or contact orders@artsy.net for help.", + [ + { + text: "Cancel", + style: "cancel", }, - }, - ]) + { + text: "Retry", + onPress: () => { + this.handleCreateInquiryOfferOrder() + }, + }, + ] + ) console.log("src/lib/Scenes/Inbox/Components/Conversations/InquiryMakeOfferButton.tsx", error) } @@ -60,7 +64,9 @@ export class InquiryMakeOfferButton extends React.Component(relay.environment, { mutation: graphql` - mutation InquiryMakeOfferButtonOrderMutation($input: CommerceCreateInquiryOfferOrderWithArtworkInput!) { + mutation InquiryMakeOfferButtonOrderMutation( + $input: CommerceCreateInquiryOfferOrderWithArtworkInput! + ) { createInquiryOfferOrder(input: $input) { orderOrError { __typename @@ -109,7 +115,9 @@ export class InquiryMakeOfferButton extends React.Component - this.setState({ isCommittingCreateOfferOrderMutation: false }, () => this.onMutationError(error)), + this.setState({ isCommittingCreateOfferOrderMutation: false }, () => + this.onMutationError(error) + ), }) } }) @@ -135,10 +143,13 @@ export class InquiryMakeOfferButton extends React.Component = ({ artwork }) => { artwork.href && navigate(artwork.href)}> - + diff --git a/src/lib/Scenes/Inbox/Components/Conversations/ItemShow.tsx b/src/lib/Scenes/Inbox/Components/Conversations/ItemShow.tsx index 05ad5140ac8..5db729ea6c3 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/ItemShow.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/ItemShow.tsx @@ -20,7 +20,12 @@ export const ItemShow: React.FC = ({ show }) => { show.href && navigate(show.href)}> - + diff --git a/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tests.tsx index 1fff310bedd..cc0093e4891 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tests.tsx @@ -19,7 +19,12 @@ jest.unmock("react-relay") let env: ReturnType const FakeApp = (props: MakeOfferModalTestsQueryResponse) => { - return + return ( + + ) } interface RenderComponentProps { @@ -142,7 +147,10 @@ describe("", () => { // EDITIONS describe("when artwork is edition set", () => { const tapOn = (edition: ReactTestInstance) => { - edition.props.onPress(edition.props.edition.internalID, edition.props.edition.isOfferableFromInquiry) + edition.props.onPress( + edition.props.edition.internalID, + edition.props.edition.isOfferableFromInquiry + ) } it("shows edition selection when it's an edition", () => { const wrapper = getWrapper(mockEditionsResolver) diff --git a/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tsx b/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tsx index c03abcb451a..6285b3258ec 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/MakeOfferModal.tsx @@ -1,6 +1,9 @@ import { ActionType, OwnerType } from "@artsy/cohesion" import { MakeOfferModal_artwork } from "__generated__/MakeOfferModal_artwork.graphql" -import { MakeOfferModalQuery, MakeOfferModalQueryResponse } from "__generated__/MakeOfferModalQuery.graphql" +import { + MakeOfferModalQuery, + MakeOfferModalQueryResponse, +} from "__generated__/MakeOfferModalQuery.graphql" import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader" import { dismissModal } from "lib/navigation/navigate" import { defaultEnvironment } from "lib/relay/createEnvironment" @@ -86,7 +89,8 @@ export const MakeOfferModal: React.FC = ({ ...props }) => { - Making an offer doesn’t guarantee you the work, as the seller might be receiving competing offers. + Making an offer doesn’t guarantee you the work, as the seller might be receiving + competing offers. diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Message.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Message.tsx index 580fea60927..5daee1e4d0f 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Message.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Message.tsx @@ -98,7 +98,12 @@ export class Message extends React.Component { const backgroundColor = color(isFromUser ? "black100" : "black10") return ( <> - + { {!!message.attachments?.length && } {this.renderAttachmentPreviews(message.attachments, backgroundColor)} - {!!showTimeSince && } + {!!showTimeSince && ( + + )} ) }} diff --git a/src/lib/Scenes/Inbox/Components/Conversations/MessageGroup.tsx b/src/lib/Scenes/Inbox/Components/Conversations/MessageGroup.tsx index 23207cbe794..57f2c03d529 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/MessageGroup.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/MessageGroup.tsx @@ -71,7 +71,10 @@ const IndividualMessage: React.FC<{ {subjectItem?.__typename === "Artwork" && ( - navigate(subjectItem.href!)} /> + navigate(subjectItem.href!)} + /> )} {subjectItem?.__typename === "Show" && ( navigate(subjectItem.href!)} /> diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Messages.tests.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Messages.tests.tsx index 574b654e801..3db6c0591a2 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Messages.tests.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Messages.tests.tsx @@ -61,7 +61,9 @@ const TestRenderer = () => ( const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -86,7 +88,9 @@ const withConversationItems = ( wrapperGetter: typeof getWrapper, { events = [], - messages = [{ createdAt: new Date("1970-12-25").toISOString(), body: "First message", attachments: [] }], + messages = [ + { createdAt: new Date("1970-12-25").toISOString(), body: "First message", attachments: [] }, + ], }: { events?: any; messages?: any } ) => { return wrapperGetter({ diff --git a/src/lib/Scenes/Inbox/Components/Conversations/Messages.tsx b/src/lib/Scenes/Inbox/Components/Conversations/Messages.tsx index caffe11a3d3..ed4e044ce84 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/Messages.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/Messages.tsx @@ -27,13 +27,17 @@ const LoadingIndicator = styled.ActivityIndicator` ` type Order = NonNullable< - NonNullable["edges"]>[number]>["node"] + NonNullable< + NonNullable["edges"]>[number] + >["node"] > type OrderEvent = Order["orderHistory"][number] type OrderEventWithKey = OrderEvent & { key: string } export type ConversationMessage = NonNullable< - NonNullable["edges"]>[number]>["node"] + NonNullable< + NonNullable["edges"]>[number] + >["node"] > export const Messages: React.FC = forwardRef((props, ref) => { @@ -61,7 +65,13 @@ export const Messages: React.FC = forwardRef((props, ref) => { .map((event, index) => ({ ...event, key: `event-${index}` })) const orderEventsWithoutFailedPayment = allOrderEvents.filter((event, index) => { - if (!(event.state === "APPROVED" && allOrderEvents[index + 1] && allOrderEvents[index + 1].state === "SUBMITTED")) { + if ( + !( + event.state === "APPROVED" && + allOrderEvents[index + 1] && + allOrderEvents[index + 1].state === "SUBMITTED" + ) + ) { return event } }) diff --git a/src/lib/Scenes/Inbox/Components/Conversations/NoMessages.tsx b/src/lib/Scenes/Inbox/Components/Conversations/NoMessages.tsx index eda50d7f449..ee1da8b9c84 100644 --- a/src/lib/Scenes/Inbox/Components/Conversations/NoMessages.tsx +++ b/src/lib/Scenes/Inbox/Components/Conversations/NoMessages.tsx @@ -23,9 +23,17 @@ export const NoMessages: React.FC = () => { Keep track of your conversations with galleries. - - Contact galleries to learn more about works you want to collect. Use your inbox to stay on top of your - inquiries. + + Contact galleries to learn more about works you want to collect. Use your inbox to stay on + top of your inquiries. diff --git a/src/lib/Scenes/NewWorksForYou/NewWorksForYou.tsx b/src/lib/Scenes/NewWorksForYou/NewWorksForYou.tsx index db621df73b0..ae431d06d2b 100644 --- a/src/lib/Scenes/NewWorksForYou/NewWorksForYou.tsx +++ b/src/lib/Scenes/NewWorksForYou/NewWorksForYou.tsx @@ -24,7 +24,9 @@ const NewWorksForYou: React.FC = ({ me, relay }) => { const { hasMore, loadMore } = relay return ( - + {!!me.artworks?.edges?.length ? ( diff --git a/src/lib/Scenes/Onboarding/ForgotPassword.tests.tsx b/src/lib/Scenes/Onboarding/ForgotPassword.tests.tsx index 458339caffc..f31665164a5 100644 --- a/src/lib/Scenes/Onboarding/ForgotPassword.tests.tsx +++ b/src/lib/Scenes/Onboarding/ForgotPassword.tests.tsx @@ -32,7 +32,11 @@ jest.mock("formik", () => ({ describe("ForgotPassword", () => { const TestProvider = () => { return ( - + ) } diff --git a/src/lib/Scenes/Onboarding/ForgotPassword.tsx b/src/lib/Scenes/Onboarding/ForgotPassword.tsx index ed1f289abc1..47884afd7cf 100644 --- a/src/lib/Scenes/Onboarding/ForgotPassword.tsx +++ b/src/lib/Scenes/Onboarding/ForgotPassword.tsx @@ -16,7 +16,8 @@ export interface ForgotPasswordValuesSchema { email: string } -export interface ForgotPasswordProps extends StackScreenProps {} +export interface ForgotPasswordProps + extends StackScreenProps {} export interface ForgotPasswordFormProps extends ForgotPasswordProps { requestedPasswordReset: boolean inputRef?: React.Ref @@ -40,7 +41,8 @@ export const ForgotPasswordForm: React.FC = ({ Forgot Password? - Please enter the email address associated with your Artsy account to receive a reset link. + Please enter the email address associated with your Artsy account to receive a reset + link. @@ -136,7 +138,10 @@ export const ForgotPassword: React.FC = ({ navigation, rout }) if (!res) { // For security purposes, we are returning a generic error message - setErrors({ email: "Couldn’t send reset password link. Please try again, or contact support@artsy.net" }) + setErrors({ + email: + "Couldn’t send reset password link. Please try again, or contact support@artsy.net", + }) } else { setRequestedPasswordReset(true) inputRef.current?.blur() diff --git a/src/lib/Scenes/Onboarding/Onboarding.tsx b/src/lib/Scenes/Onboarding/Onboarding.tsx index 91a3a3b3b2d..5449a028b82 100644 --- a/src/lib/Scenes/Onboarding/Onboarding.tsx +++ b/src/lib/Scenes/Onboarding/Onboarding.tsx @@ -1,6 +1,13 @@ import { NavigationContainer } from "@react-navigation/native" -import { CardStyleInterpolators, createStackNavigator, TransitionPresets } from "@react-navigation/stack" -import { ArtsyKeyboardAvoidingView, ArtsyKeyboardAvoidingViewContext } from "lib/Components/ArtsyKeyboardAvoidingView" +import { + CardStyleInterpolators, + createStackNavigator, + TransitionPresets, +} from "@react-navigation/stack" +import { + ArtsyKeyboardAvoidingView, + ArtsyKeyboardAvoidingViewContext, +} from "lib/Components/ArtsyKeyboardAvoidingView" import { ArtsyWebViewPrivacy, ArtsyWebViewTerms } from "lib/Components/ArtsyReactWebViewPolicy" import { GlobalStore } from "lib/store/GlobalStore" import { NetworkAwareProvider } from "lib/utils/NetworkAwareProvider" @@ -68,8 +75,15 @@ export const OnboardingWelcomeScreens = () => { : CardStyleInterpolators.forHorizontalIOS, })} /> - - + + @@ -86,7 +100,11 @@ export const Onboarding = () => { value={{ isVisible: true, isPresentedModally: false, bottomOffset: 0 }} > - {onboardingState === "incomplete" ? : } + {onboardingState === "incomplete" ? ( + + ) : ( + + )} {!!showNetworkUnavailableModal && } diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/EmailSubscriptionCheckbox.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/EmailSubscriptionCheckbox.tsx index fbfe090c7db..fd78f2c24ec 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/EmailSubscriptionCheckbox.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/EmailSubscriptionCheckbox.tsx @@ -8,14 +8,18 @@ interface EmailSubscriptionCheckboxProps { error?: boolean } -export const EmailSubscriptionCheckbox: React.FC = ({ setChecked, checked, error }) => { +export const EmailSubscriptionCheckbox: React.FC = ({ + setChecked, + checked, + error, +}) => { return ( setChecked(!checked)}> setChecked(!checked)} mt={0.3}> - Dive deeper into the art market with Artsy emails. Subscribe to hear about our products, services, - editorials, and other promotional content. Unsubscribe at any time. + Dive deeper into the art market with Artsy emails. Subscribe to hear about our products, + services, editorials, and other promotional content. Unsubscribe at any time. diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccount.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccount.tsx index 88fb139558b..a876f435143 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccount.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccount.tsx @@ -15,7 +15,10 @@ import { Alert, Animated, ScrollView } from "react-native" import * as Yup from "yup" import { OnboardingNavigationStack } from "../Onboarding" import { OnboardingSocialPick } from "../OnboardingSocialPick" -import { OnboardingCreateAccountEmail, OnboardingCreateAccountEmailParams } from "./OnboardingCreateAccountEmail" +import { + OnboardingCreateAccountEmail, + OnboardingCreateAccountEmailParams, +} from "./OnboardingCreateAccountEmail" import { OnboardingCreateAccountName } from "./OnboardingCreateAccountName" import { OnboardingCreateAccountPassword } from "./OnboardingCreateAccountPassword" @@ -39,9 +42,10 @@ export type OnboardingCreateAccountNavigationStack = { const StackNavigator = createStackNavigator() // tslint:disable-next-line:variable-name -export const __unsafe__createAccountNavigationRef: React.MutableRefObject = { - current: null, -} +export const __unsafe__createAccountNavigationRef: React.MutableRefObject = + { + current: null, + } export interface UserSchema { email: string @@ -55,7 +59,9 @@ export interface FormikSchema extends UserSchema { } export const emailSchema = Yup.object().shape({ - email: Yup.string().email("Please provide a valid email address").required("Email field is required"), + email: Yup.string() + .email("Please provide a valid email address") + .required("Email field is required"), }) export const passwordSchema = Yup.object().shape({ password: Yup.string() @@ -76,14 +82,25 @@ export const getCurrentRoute = () => const EMAIL_EXISTS_ERROR_MESSAGE = "We found an account with this email" -export const OnboardingCreateAccountWithEmail: React.FC = ({ navigation }) => { +export const OnboardingCreateAccountWithEmail: React.FC = ({ + navigation, +}) => { const formik = useFormik({ enableReinitialize: true, validateOnChange: false, validateOnBlur: true, - initialValues: { email: "", password: "", name: "", acceptedTerms: false, agreedToReceiveEmails: false }, + initialValues: { + email: "", + password: "", + name: "", + acceptedTerms: false, + agreedToReceiveEmails: false, + }, initialErrors: {}, - onSubmit: async ({ email, password, name, agreedToReceiveEmails, acceptedTerms }, { setErrors }) => { + onSubmit: async ( + { email, password, name, agreedToReceiveEmails, acceptedTerms }, + { setErrors } + ) => { switch (getCurrentRoute()) { case "OnboardingCreateAccountEmail": const userExists = await GlobalStore.actions.auth.userExists({ email }) @@ -95,7 +112,9 @@ export const OnboardingCreateAccountWithEmail: React.FC - - + + { - navigation.replace("OnboardingLoginWithEmail", { withFadeAnimation: true, email: formik.values.email }) + navigation.replace("OnboardingLoginWithEmail", { + withFadeAnimation: true, + email: formik.values.email, + }) }} /> @@ -172,12 +200,9 @@ interface OnboardingCreateAccountScreenWrapperProps { caption?: string } -export const OnboardingCreateAccountScreenWrapper: React.FC = ({ - onBackButtonPress, - title, - caption, - children, -}) => { +export const OnboardingCreateAccountScreenWrapper: React.FC< + OnboardingCreateAccountScreenWrapperProps +> = ({ onBackButtonPress, title, caption, children }) => { const color = useColor() return ( diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountEmail.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountEmail.tsx index fce24ae6165..7583165854b 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountEmail.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountEmail.tsx @@ -15,9 +15,14 @@ export interface OnboardingCreateAccountEmailParams { } interface OnboardingCreateAccountEmailProps - extends StackScreenProps {} + extends StackScreenProps< + OnboardingCreateAccountNavigationStack, + "OnboardingCreateAccountEmail" + > {} -export const OnboardingCreateAccountEmail: React.FC = ({ route }) => { +export const OnboardingCreateAccountEmail: React.FC = ({ + route, +}) => { const color = useColor() const { values, handleChange, errors, setErrors, handleSubmit } = useFormikContext() diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tests.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tests.tsx index c189e297106..087b52c2d22 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tests.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tests.tsx @@ -16,11 +16,11 @@ const navigationMock = { const onSubmitMock = jest.fn() describe("OnboardingCreateAccountName", () => { - const Test: React.FC<{ name?: string; acceptedTerms?: boolean; agreedToReceiveEmails?: boolean }> = ({ - name = "", - acceptedTerms = false, - agreedToReceiveEmails = false, - }) => { + const Test: React.FC<{ + name?: string + acceptedTerms?: boolean + agreedToReceiveEmails?: boolean + }> = ({ name = "", acceptedTerms = false, agreedToReceiveEmails = false }) => { const formik = useFormik({ enableReinitialize: true, validateOnChange: false, diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tsx index 485959791e5..ace022126df 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountName.tsx @@ -15,9 +15,12 @@ import { TermsOfServiceCheckbox } from "./TermsOfServiceCheckbox" export interface OnboardingCreateAccountNameProps extends StackScreenProps {} -export const OnboardingCreateAccountName: React.FC = ({ navigation }) => { +export const OnboardingCreateAccountName: React.FC = ({ + navigation, +}) => { const color = useColor() - const { values, handleSubmit, handleChange, errors, setErrors, setFieldValue } = useFormikContext() + const { values, handleSubmit, handleChange, errors, setErrors, setFieldValue } = + useFormikContext() const [highlightTerms, setHighlightTerms] = useState(false) return ( diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tests.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tests.tsx index 7e4a93844db..e68e12235f4 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tests.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tests.tsx @@ -72,7 +72,9 @@ describe("OnboardingCreateAccountPassword", () => { input.props.onChangeText("missing1uppercase") input.props.onSubmitEditing() await flushPromiseQueue() - expect(input.props.error).toEqual("Your password should contain at least one uppercase letter") + expect(input.props.error).toEqual( + "Your password should contain at least one uppercase letter" + ) input.props.onChangeText("Nodigits") input.props.onSubmitEditing() @@ -82,7 +84,9 @@ describe("OnboardingCreateAccountPassword", () => { input.props.onChangeText("MISSING1LOWERCASE") input.props.onSubmitEditing() await flushPromiseQueue() - expect(input.props.error).toEqual("Your password should contain at least one lowercase letter") + expect(input.props.error).toEqual( + "Your password should contain at least one lowercase letter" + ) input.props.onChangeText("") input.props.onSubmitEditing() diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tsx index 670c7855a04..1859706bbcf 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingCreateAccountPassword.tsx @@ -10,9 +10,14 @@ import { } from "./OnboardingCreateAccount" interface OnboardingCreateAccountPasswordProps - extends StackScreenProps {} + extends StackScreenProps< + OnboardingCreateAccountNavigationStack, + "OnboardingCreateAccountPassword" + > {} -export const OnboardingCreateAccountPassword: React.FC = ({ navigation }) => { +export const OnboardingCreateAccountPassword: React.FC = ({ + navigation, +}) => { const color = useColor() const { values, handleSubmit, handleChange, errors, setErrors } = useFormikContext() diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingSocialPick.tests.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingSocialPick.tests.tsx index 810ae0708a9..3182c97c839 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingSocialPick.tests.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/OnboardingSocialPick.tests.tsx @@ -66,7 +66,9 @@ describe("OnboardingSocialPick", () => { const tree = renderWithWrappers() tree.root.findByProps({ testID: "useApple" }).props.onPress() - expect(GlobalStore.actions.auth.authApple).toHaveBeenCalledWith({ agreedToReceiveEmails: true }) + expect(GlobalStore.actions.auth.authApple).toHaveBeenCalledWith({ + agreedToReceiveEmails: true, + }) }) }) }) diff --git a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/TermsOfServiceCheckbox.tsx b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/TermsOfServiceCheckbox.tsx index e9cfe63985a..c21b1dac36d 100644 --- a/src/lib/Scenes/Onboarding/OnboardingCreateAccount/TermsOfServiceCheckbox.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingCreateAccount/TermsOfServiceCheckbox.tsx @@ -27,7 +27,9 @@ export const TermsOfServiceCheckbox: React.FC = ({ By checking this box, you consent to our{" "} (isiOS ? navigate("/terms", { modal: true }) : navigation.navigate("Terms"))} + onPress={() => + isiOS ? navigate("/terms", { modal: true }) : navigation.navigate("Terms") + } variant="xs" style={{ textDecorationLine: "underline" }} > @@ -35,7 +37,9 @@ export const TermsOfServiceCheckbox: React.FC = ({ ,{" "} (isiOS ? navigate("/privacy", { modal: true }) : navigation.navigate("Privacy"))} + onPress={() => + isiOS ? navigate("/privacy", { modal: true }) : navigation.navigate("Privacy") + } variant="xs" style={{ textDecorationLine: "underline" }} > @@ -44,7 +48,9 @@ export const TermsOfServiceCheckbox: React.FC = ({ , and{" "} - isiOS ? navigate("/conditions-of-sale", { modal: true }) : navigation.navigate("ConditionsOfSale") + isiOS + ? navigate("/conditions-of-sale", { modal: true }) + : navigation.navigate("ConditionsOfSale") } variant="xs" style={{ textDecorationLine: "underline" }} diff --git a/src/lib/Scenes/Onboarding/OnboardingLogin.tests.tsx b/src/lib/Scenes/Onboarding/OnboardingLogin.tests.tsx index 7e5880e81c6..8499872ac8c 100644 --- a/src/lib/Scenes/Onboarding/OnboardingLogin.tests.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingLogin.tests.tsx @@ -30,7 +30,12 @@ jest.mock("formik", () => ({ describe("OnboardingLogin", () => { const TestProvider = ({ email = "" }) => { - return + return ( + + ) } describe("Forget Button", () => { diff --git a/src/lib/Scenes/Onboarding/OnboardingLogin.tsx b/src/lib/Scenes/Onboarding/OnboardingLogin.tsx index 173634d0e34..086d3e0ba49 100644 --- a/src/lib/Scenes/Onboarding/OnboardingLogin.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingLogin.tsx @@ -15,7 +15,8 @@ export const OnboardingLogin: React.FC = () => { return } -export interface OnboardingLoginProps extends StackScreenProps {} +export interface OnboardingLoginProps + extends StackScreenProps {} export interface OnboardingLoginValuesSchema { email: string @@ -27,10 +28,22 @@ export const loginSchema = Yup.object().shape({ password: Yup.string().test("password", "Password field is required", (value) => value !== ""), }) -export const OnboardingLoginWithEmailForm: React.FC = ({ navigation, route }) => { +export const OnboardingLoginWithEmailForm: React.FC = ({ + navigation, + route, +}) => { const color = useColor() - const { values, handleSubmit, handleChange, validateForm, errors, isValid, dirty, isSubmitting, setErrors } = - useFormikContext() + const { + values, + handleSubmit, + handleChange, + validateForm, + errors, + isValid, + dirty, + isSubmitting, + setErrors, + } = useFormikContext() const passwordInputRef = useRef(null) const emailInputRef = useRef(null) @@ -59,7 +72,10 @@ export const OnboardingLoginWithEmailForm: React.FC = ({ n return ( diff --git a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tests.tsx b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tests.tsx index 54d0999a63e..051a2383144 100644 --- a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tests.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tests.tsx @@ -22,7 +22,8 @@ describe("OnboardingPersonalizationList", () => { environment={mockEnvironment} query={graphql` - query OnboardingPersonalizationTestsQuery($excludeArtistIDs: [String]) @relay_test_operation { + query OnboardingPersonalizationTestsQuery($excludeArtistIDs: [String]) + @relay_test_operation { highlights { popularArtists(excludeFollowedArtists: true, excludeArtistIDs: $excludeArtistIDs) { internalID @@ -80,7 +81,9 @@ describe("OnboardingPersonalizationList", () => { jest.runAllTimers() expect(__globalStoreTestUtils__?.getCurrentState().auth.onboardingState).toEqual("complete") - expect(LegacyNativeModules.ARTemporaryAPIModule.requestPrepromptNotificationPermissions).toBeCalled() + expect( + LegacyNativeModules.ARTemporaryAPIModule.requestPrepromptNotificationPermissions + ).toBeCalled() }) }) }) diff --git a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tsx b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tsx index 8812545f7c2..7408cbcc78c 100644 --- a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalization.tsx @@ -2,7 +2,10 @@ import { NavigationContainer } from "@react-navigation/native" import { createStackNavigator, StackScreenProps, TransitionPresets } from "@react-navigation/stack" import { OnboardingPersonalization_highlights } from "__generated__/OnboardingPersonalization_highlights.graphql" import { OnboardingPersonalizationListQuery } from "__generated__/OnboardingPersonalizationListQuery.graphql" -import { ArtistListItemContainer as ArtistListItem, ArtistListItemPlaceholder } from "lib/Components/ArtistListItem" +import { + ArtistListItemContainer as ArtistListItem, + ArtistListItemPlaceholder, +} from "lib/Components/ArtistListItem" import SearchIcon from "lib/Icons/SearchIcon" import { GlobalStore } from "lib/store/GlobalStore" import { renderWithPlaceholder } from "lib/utils/renderWithPlaceholder" @@ -48,13 +51,20 @@ export const OnboardingPersonalization = () => { } interface OnboardingPersonalizationListNavigationProps - extends StackScreenProps {} + extends StackScreenProps< + OnboardingPersonalizationNavigationStack, + "OnboardingPersonalizationList" + > {} interface OnboardingPersonalizationListProps extends OnboardingPersonalizationListNavigationProps { highlights: OnboardingPersonalization_highlights } -const OnboardingPersonalizationListHeader = ({ navigateToModal }: { navigateToModal: () => void }) => { +const OnboardingPersonalizationListHeader = ({ + navigateToModal, +}: { + navigateToModal: () => void +}) => { const color = useColor() return ( <> @@ -69,7 +79,8 @@ const OnboardingPersonalizationListHeader = ({ navigateToModal }: { navigateToMo What Artists do You Collect? - Follow at least three artists you’re looking to collect or track so we can personalize your experience. + Follow at least three artists you’re looking to collect or track so we can personalize + your experience. @@ -77,7 +88,12 @@ const OnboardingPersonalizationListHeader = ({ navigateToModal }: { navigateToMo {/* Fake search Input */} - + @@ -93,7 +109,9 @@ const OnboardingPersonalizationListHeader = ({ navigateToModal }: { navigateToMo ) } -export const OnboardingPersonalizationList: React.FC = ({ ...props }) => { +export const OnboardingPersonalizationList: React.FC = ({ + ...props +}) => { const space = useSpace() const popularArtists = compact(props.highlights.popularArtists) @@ -128,7 +146,12 @@ export const OnboardingPersonalizationList: React.FC - @@ -141,19 +164,24 @@ const handleFinishOnboardingPersonalization = async () => { GlobalStore.actions.auth.requestPushNotifPermission() } -export const OnboardingPersonalizationListRefetchContainer = createFragmentContainer(OnboardingPersonalizationList, { - highlights: graphql` - fragment OnboardingPersonalization_highlights on Highlights - @argumentDefinitions(excludeArtistIDs: { type: "[String]" }) { - popularArtists(excludeFollowedArtists: true, excludeArtistIDs: $excludeArtistIDs) { - internalID - ...ArtistListItem_artist +export const OnboardingPersonalizationListRefetchContainer = createFragmentContainer( + OnboardingPersonalizationList, + { + highlights: graphql` + fragment OnboardingPersonalization_highlights on Highlights + @argumentDefinitions(excludeArtistIDs: { type: "[String]" }) { + popularArtists(excludeFollowedArtists: true, excludeArtistIDs: $excludeArtistIDs) { + internalID + ...ArtistListItem_artist + } } - } - `, -}) + `, + } +) -const OnboardingPersonalizationListQueryRenderer: React.FC = (props) => ( +const OnboardingPersonalizationListQueryRenderer: React.FC< + OnboardingPersonalizationListNavigationProps +> = (props) => ( environment={defaultEnvironment} query={graphql` diff --git a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationArtistListItem.tsx b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationArtistListItem.tsx index 933d965f7ec..99556cd7df7 100644 --- a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationArtistListItem.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationArtistListItem.tsx @@ -14,7 +14,11 @@ import { RelayPaginationProp } from "react-relay" interface Props { artist: NonNullable< NonNullable< - NonNullable["edges"]>[0]> + NonNullable< + NonNullable< + NonNullable["edges"] + >[0] + > >["node"] > relay: RelayPaginationProp @@ -31,7 +35,11 @@ interface State { isFollowedChanging: boolean } -export const formatTombstoneText = (nationality: string | null, birthday: string | null, deathday: string | null) => { +export const formatTombstoneText = ( + nationality: string | null, + birthday: string | null, + deathday: string | null +) => { if (nationality && birthday && deathday) { return nationality.trim() + ", " + birthday + "-" + deathday } else if (nationality && birthday) { @@ -86,7 +94,9 @@ export class OnboardingPersonalizationArtistListItem extends React.Component ({ - action_name: props.artist.is_followed ? Schema.ActionNames.ArtistFollow : Schema.ActionNames.ArtistUnfollow, + action_name: props.artist.is_followed + ? Schema.ActionNames.ArtistFollow + : Schema.ActionNames.ArtistUnfollow, action_type: Schema.ActionTypes.Success, owner_id: props.artist.internalID, owner_slug: props.artist.slug, diff --git a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tests.tsx b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tests.tsx index dc8da90ed5e..a93b7df03d2 100644 --- a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tests.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tests.tsx @@ -19,7 +19,8 @@ describe("OnboardingPersonalizationModal", () => { environment={mockEnvironment} query={graphql` - query OnboardingPersonalizationModalTestsQuery($query: String!, $count: Int!) @relay_test_operation { + query OnboardingPersonalizationModalTestsQuery($query: String!, $count: Int!) + @relay_test_operation { ...OnboardingPersonalizationModal_artists @arguments(query: $query, count: $count) } `} @@ -88,6 +89,8 @@ describe("OnboardingPersonalizationModal", () => { const noResults = tree.root.findByProps({ testID: "noResults" }) - expect(extractText(noResults)).toContain("We couldn't find anything for “artist with no results”") + expect(extractText(noResults)).toContain( + "We couldn't find anything for “artist with no results”" + ) }) }) diff --git a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tsx b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tsx index 187ea59f699..f89bc9627f8 100644 --- a/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingPersonalization/OnboardingPersonalizationModal.tsx @@ -18,7 +18,10 @@ import { OnboardingPersonalizationNavigationStack } from "./OnboardingPersonaliz import { OnboardingPersonalizationArtistListItem } from "./OnboardingPersonalizationArtistListItem" interface OnboardingPersonalizationModalNavigationProps - extends StackScreenProps {} + extends StackScreenProps< + OnboardingPersonalizationNavigationStack, + "OnboardingPersonalizationModal" + > {} interface OnboardingPersonalizationListProps extends OnboardingPersonalizationModalNavigationProps { artists: OnboardingPersonalizationModal_artists @@ -78,7 +81,9 @@ const OnboardingPersonalizationModal: React.FC props.relay.isLoading(), [props.relay]) + const isLoading = !__TEST__ + ? props.relay.isLoading() + : useMemo(() => props.relay.isLoading(), [props.relay]) return ( = ( - initialProps -) => ( +export const OnboardingPersonalizationModalQueryRenderer: React.FC< + OnboardingPersonalizationModalNavigationProps +> = (initialProps) => ( render={({ props, error }) => { if (error) { @@ -213,7 +231,9 @@ export const OnboardingPersonalizationModalQueryRenderer: React.FC } - return + return ( + + ) }} cacheConfig={{ force: true }} variables={{ diff --git a/src/lib/Scenes/Onboarding/OnboardingSocialPick.tsx b/src/lib/Scenes/Onboarding/OnboardingSocialPick.tsx index 63dd55c0943..d1f425281a0 100644 --- a/src/lib/Scenes/Onboarding/OnboardingSocialPick.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingSocialPick.tsx @@ -38,7 +38,10 @@ export const OnboardingSocialPick: React.FC = ({ mode if (mode === "login") { await GlobalStore.actions.auth.authFacebook({ signInOrUp: "signIn" }) } else { - await GlobalStore.actions.auth.authFacebook({ signInOrUp: "signUp", agreedToReceiveEmails: true }) + await GlobalStore.actions.auth.authFacebook({ + signInOrUp: "signUp", + agreedToReceiveEmails: true, + }) } } catch (error) { if (typeof error === "string") { @@ -52,7 +55,10 @@ export const OnboardingSocialPick: React.FC = ({ mode if (mode === "login") { await GlobalStore.actions.auth.authGoogle({ signInOrUp: "signIn" }) } else { - await GlobalStore.actions.auth.authGoogle({ signInOrUp: "signUp", agreedToReceiveEmails: true }) + await GlobalStore.actions.auth.authGoogle({ + signInOrUp: "signUp", + agreedToReceiveEmails: true, + }) } } catch (error) { if (typeof error === "string") { @@ -110,7 +116,13 @@ export const OnboardingSocialPick: React.FC = ({ mode mb={1} variant="fillDark" iconPosition="left-start" - icon={} + icon={ + + } testID="useApple" > Continue with Apple @@ -125,7 +137,11 @@ export const OnboardingSocialPick: React.FC = ({ mode variant="outline" iconPosition="left-start" icon={ - + } testID="useGoogle" > @@ -141,7 +157,11 @@ export const OnboardingSocialPick: React.FC = ({ mode variant="outline" iconPosition="left-start" icon={ - + } testID="useFacebook" > @@ -154,7 +174,9 @@ export const OnboardingSocialPick: React.FC = ({ mode {!!enableGoogleAuth ? ", Google" : ""} {isiOS ? " or Apple" : ""}, you agree to Artsy's{" "} (isiOS ? navigate("/terms", { modal: true }) : navigation.navigate("Terms"))} + onPress={() => + isiOS ? navigate("/terms", { modal: true }) : navigation.navigate("Terms") + } variant="xs" style={{ textDecorationLine: "underline" }} testID="openTerms" @@ -163,7 +185,9 @@ export const OnboardingSocialPick: React.FC = ({ mode {" "} and{" "} (isiOS ? navigate("/privacy", { modal: true }) : navigation.navigate("Privacy"))} + onPress={() => + isiOS ? navigate("/privacy", { modal: true }) : navigation.navigate("Privacy") + } variant="xs" style={{ textDecorationLine: "underline" }} testID="openPrivacy" diff --git a/src/lib/Scenes/Onboarding/OnboardingWelcome.tsx b/src/lib/Scenes/Onboarding/OnboardingWelcome.tsx index b10bbbe863e..87972a65ab7 100644 --- a/src/lib/Scenes/Onboarding/OnboardingWelcome.tsx +++ b/src/lib/Scenes/Onboarding/OnboardingWelcome.tsx @@ -10,7 +10,8 @@ import Animated, { Easing } from "react-native-reanimated" import backgoundImage from "../../../../images/WelcomeImage.webp" import { OnboardingNavigationStack } from "./Onboarding" -interface OnboardingWelcomeProps extends StackScreenProps {} +interface OnboardingWelcomeProps + extends StackScreenProps {} const imgProps = Image.resolveAssetSource(backgoundImage) @@ -114,7 +115,13 @@ export const OnboardingWelcome: React.FC = ({ navigation Collect Art by the World’s Leading Artists diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/ArtworkInfoSection.tests.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/ArtworkInfoSection.tests.tsx index bdd6b7a51f1..d8e5863765a 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/ArtworkInfoSection.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/ArtworkInfoSection.tests.tsx @@ -63,7 +63,9 @@ describe("ArtworkInfoSection", () => { }) expect(tree.findByProps({ testID: "date" }).props.children).toBe("2017") - expect(tree.findByProps({ testID: "medium" }).props.children).toBe("Rayon thread on poly twill backed") + expect(tree.findByProps({ testID: "medium" }).props.children).toBe( + "Rayon thread on poly twill backed" + ) expect(tree.findByProps({ testID: "title" }).props.children).toBe( "Set of Six (Six) Scout Series Embroidered Patches, " diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/ArtworkInfoSection.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/ArtworkInfoSection.tsx index 3eae3461a5c..0e6ead2440c 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/ArtworkInfoSection.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/ArtworkInfoSection.tsx @@ -52,7 +52,9 @@ export const ArtworkInfoSection: React.FC = ({ artwork }) => { {!!dimensions?.in && !!dimensions?.cm && ( - {LegacyNativeModules.ARCocoaConstantsModule.CurrentLocale === "en_US" ? dimensions!.in : dimensions!.cm} + {LegacyNativeModules.ARCocoaConstantsModule.CurrentLocale === "en_US" + ? dimensions!.in + : dimensions!.cm} )} diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetails.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetails.tsx index 3730c9a46c7..0ce9f54e4ee 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetails.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetails.tsx @@ -45,7 +45,9 @@ const OrderDetails: FC = ({ order }) => { const DATA: SectionListItem[] = compact([ { key: "OrderDetailsHeader", - data: [], + data: [ + , + ], }, { key: "Artwork_Info", @@ -60,12 +62,16 @@ const OrderDetails: FC = ({ order }) => { { key: "Payment_Method", title: "Payment Method", - data: [], + data: [ + , + ], }, isShipping && { key: "TrackOrder_Section", title: "Track Order", - data: [], + data: [ + , + ], }, isShipping && { key: "ShipTo_Section", diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsHeader.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsHeader.tsx index 60db20c5164..9f595ce999b 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsHeader.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsHeader.tsx @@ -43,7 +43,13 @@ export const OrderDetailsHeader: React.FC = ({ info }) => { {code} - + {orderStatus} diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsPayment.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsPayment.tsx index abe1fef217d..8a1a18f15c4 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsPayment.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/OrderDetailsPayment.tsx @@ -16,7 +16,11 @@ const CreditCardDetails: React.FC = ({ order }) => { {creditCard ? ( - + diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/ShipsToSection.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/ShipsToSection.tsx index 4c6fc056071..eddc76a6784 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/ShipsToSection.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/ShipsToSection.tsx @@ -9,7 +9,10 @@ interface Props { } export const ShipsToSection: React.FC = ({ address }) => { - if (!address.requestedFulfillment || address.requestedFulfillment.__typename === "CommercePickup") { + if ( + !address.requestedFulfillment || + address.requestedFulfillment.__typename === "CommercePickup" + ) { return null } @@ -17,7 +20,8 @@ export const ShipsToSection: React.FC = ({ address }) => { address.requestedFulfillment.__typename === "CommerceShip" || address.requestedFulfillment.__typename === "CommerceShipArta" ) { - const { city, addressLine1, addressLine2, region, postalCode, country, phoneNumber } = address.requestedFulfillment + const { city, addressLine1, addressLine2, region, postalCode, country, phoneNumber } = + address.requestedFulfillment const addedComma = city ? "," : "" return ( diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/SummarySection.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/SummarySection.tsx index d655c7b83b1..8aafca27544 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/SummarySection.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/SummarySection.tsx @@ -9,9 +9,12 @@ interface Props { } export const SummarySection: React.FC = ({ section }) => { - const { buyerTotal, taxTotal, shippingTotal, totalListPrice, lineItems, mode, lastOffer } = section + const { buyerTotal, taxTotal, shippingTotal, totalListPrice, lineItems, mode, lastOffer } = + section const { selectedShippingQuote } = extractNodes(lineItems)?.[0] || {} - const shippingName = selectedShippingQuote?.displayName ? `${selectedShippingQuote.displayName} delivery` : "Shipping" + const shippingName = selectedShippingQuote?.displayName + ? `${selectedShippingQuote.displayName} delivery` + : "Shipping" const isBuyOrder = mode === "BUY" const isBuyerOffer = !lastOffer || lastOffer.fromParticipant === "BUYER" diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/Components/TrackOrderSection.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/Components/TrackOrderSection.tsx index 00752a77cac..9d31c716f69 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/Components/TrackOrderSection.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/Components/TrackOrderSection.tsx @@ -47,7 +47,9 @@ export const TrackOrderSection: FC = ({ section }) => { Shipped on  - {DateTime.fromISO(shipment?.deliveryStart || createdAt).toLocaleString(DateTime.DATE_MED)} + {DateTime.fromISO(shipment?.deliveryStart || createdAt).toLocaleString( + DateTime.DATE_MED + )} )} @@ -76,7 +78,13 @@ export const TrackOrderSection: FC = ({ section }) => { )} {!!trackingUrl && ( - )} diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetails.tests.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetails.tests.tsx index e3955aa357a..70f740bf2c9 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetails.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetails.tests.tsx @@ -122,7 +122,9 @@ describe(OrderDetailsQueryRender, () => { }) it("Loads OrderHistoryQueryRender with OrderDetailsPlaceholder", () => { - const tree = renderWithWrappers().root + const tree = renderWithWrappers( + + ).root expect(tree.findAllByType(OrderDetailsPlaceholder)).toHaveLength(1) }) }) diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsHeader.tests.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsHeader.tests.tsx index eb5ecb0d585..273848178b6 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsHeader.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsHeader.tests.tsx @@ -65,7 +65,9 @@ describe("OrderDetailsHeader", () => { it("APPROVED state", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...mockInfo, state: "APPROVED" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...mockInfo, state: "APPROVED" }), + }) expect(extractText(tree.findByProps({ testID: "status" }))).toBe("confirmed") expect(extractText(tree.findByProps({ testID: "fulfillment" }))).toBe("Delivery") @@ -73,7 +75,9 @@ describe("OrderDetailsHeader", () => { it("FULFILLED state", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...mockInfo, state: "FULFILLED" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...mockInfo, state: "FULFILLED" }), + }) expect(extractText(tree.findByProps({ testID: "status" }))).toBe("delivered") expect(extractText(tree.findByProps({ testID: "fulfillment" }))).toBe("Delivery") @@ -164,7 +168,10 @@ describe("OrderDetailsHeader", () => { it("SUBMITTED state", () => { const tree = renderWithWrappers().root mockEnvironmentPayload(mockEnvironment, { - CommerceOrder: () => ({ ...mockInfo, requestedFulfillment: { __typename: "CommercePickup" } }), + CommerceOrder: () => ({ + ...mockInfo, + requestedFulfillment: { __typename: "CommercePickup" }, + }), }) expect(extractText(tree.findByProps({ testID: "status" }))).toBe("pending") diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsPayment.tests.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsPayment.tests.tsx index f52526fc861..5c1eef1c8e7 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsPayment.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/OrderDetailsPayment.tests.tsx @@ -59,7 +59,9 @@ describe("PaymentSection", () => { }), }) - expect(extractText(tree.root.findByProps({ testID: "credit-card-info" }))).toEqual(`visa ending in 4242`) + expect(extractText(tree.root.findByProps({ testID: "credit-card-info" }))).toEqual( + `visa ending in 4242` + ) }) it("renders when credit card doesn't exist", () => { diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/SoldBySection.tests.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/SoldBySection.tests.tsx index 63070b47f0a..3baca8b15ce 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/SoldBySection.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/SoldBySection.tests.tsx @@ -63,7 +63,9 @@ describe("SoldBySection", () => { }) expect(tree.findByProps({ testID: "delivery" }).props.children).toBe("Aug 10, 2021") - expect(extractText(tree.findByProps({ testID: "soldByInfo" }))).toBe("Ships from Minsk, Belarus") + expect(extractText(tree.findByProps({ testID: "soldByInfo" }))).toBe( + "Ships from Minsk, Belarus" + ) }) it("renders correctly for pick up fulfillment", () => { diff --git a/src/lib/Scenes/OrderHistory/OrderDetails/TrackOrderSection.tests.tsx b/src/lib/Scenes/OrderHistory/OrderDetails/TrackOrderSection.tests.tsx index 49808e4f36f..7a36536e6a3 100644 --- a/src/lib/Scenes/OrderHistory/OrderDetails/TrackOrderSection.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderDetails/TrackOrderSection.tests.tsx @@ -88,10 +88,16 @@ describe("TrackOrderSection", () => { expect(extractText(tree.findByProps({ testID: "orderStatus" }))).toBe("pending") expect(tree.findAllByProps({ testID: "trackingNumber" })).toHaveLength(0) - expect(extractText(tree.findByProps({ testID: "noTrackingNumber" }))).toBe("Tracking not available") + expect(extractText(tree.findByProps({ testID: "noTrackingNumber" }))).toBe( + "Tracking not available" + ) expect(extractText(tree.findByProps({ testID: "shippedOn" }))).toContain("Sep 2, 2021") - expect(extractText(tree.findByProps({ testID: "estimatedDelivery" }))).toContain("Oct 2, 2021") - expect(extractText(tree.findByProps({ testID: "trackingUrl" }))).toContain("View full tracking details") + expect(extractText(tree.findByProps({ testID: "estimatedDelivery" }))).toContain( + "Oct 2, 2021" + ) + expect(extractText(tree.findByProps({ testID: "trackingUrl" }))).toContain( + "View full tracking details" + ) }) it("not renders fields without data", () => { @@ -105,7 +111,9 @@ describe("TrackOrderSection", () => { expect(extractText(tree.findByProps({ testID: "orderStatus" }))).toBe("pending") expect(tree.findAllByProps({ testID: "trackingNumber" })).toHaveLength(0) - expect(extractText(tree.findByProps({ testID: "noTrackingNumber" }))).toBe("Tracking not available") + expect(extractText(tree.findByProps({ testID: "noTrackingNumber" }))).toBe( + "Tracking not available" + ) expect(tree.findAllByProps({ testID: "shippedOn" })).toHaveLength(0) expect(tree.findAllByProps({ testID: "estimatedDelivery" })).toHaveLength(0) expect(tree.findAllByProps({ testID: "trackingUrl" })).toHaveLength(0) @@ -121,8 +129,12 @@ describe("TrackOrderSection", () => { expect(extractText(tree.findByProps({ testID: "trackingNumber" }))).toContain("12345678910") expect(tree.findAllByProps({ testID: "noTrackingNumber" })).toHaveLength(0) expect(extractText(tree.findByProps({ testID: "shippedOn" }))).toContain("Oct 3, 2021") - expect(extractText(tree.findByProps({ testID: "estimatedDelivery" }))).toContain("on September 20, 2021") - expect(extractText(tree.findByProps({ testID: "trackingUrl" }))).toContain("View full tracking details") + expect(extractText(tree.findByProps({ testID: "estimatedDelivery" }))).toContain( + "on September 20, 2021" + ) + expect(extractText(tree.findByProps({ testID: "trackingUrl" }))).toContain( + "View full tracking details" + ) }) it("not renders fields without data", () => { @@ -152,7 +164,9 @@ describe("TrackOrderSection", () => { expect(extractText(tree.findByProps({ testID: "orderStatus" }))).toBe("in transit") expect(tree.findAllByProps({ testID: "trackingNumber" })).toHaveLength(0) - expect(extractText(tree.findByProps({ testID: "noTrackingNumber" }))).toBe("Tracking not available") + expect(extractText(tree.findByProps({ testID: "noTrackingNumber" }))).toBe( + "Tracking not available" + ) expect(tree.findAllByProps({ testID: "shippedOn" })).toHaveLength(0) expect(tree.findAllByProps({ testID: "estimatedDelivery" })).toHaveLength(0) expect(tree.findAllByProps({ testID: "trackingUrl" })).toHaveLength(0) @@ -164,12 +178,20 @@ describe("TrackOrderSection", () => { CommerceOrder: () => ({ ...CommerceShipArtaOrder, lineItems: { - edges: [{ node: { shipment: { status: "completed", deliveryEnd: "2021-09-02T14:51:19+03:00" } } }], + edges: [ + { + node: { + shipment: { status: "completed", deliveryEnd: "2021-09-02T14:51:19+03:00" }, + }, + }, + ], }, }), }) - expect(extractText(tree.findByProps({ testID: "deliveredStatus" }))).toBe("Delivered on Sep 2, 2021") + expect(extractText(tree.findByProps({ testID: "deliveredStatus" }))).toBe( + "Delivered on Sep 2, 2021" + ) }) }) diff --git a/src/lib/Scenes/OrderHistory/OrderHistory.tsx b/src/lib/Scenes/OrderHistory/OrderHistory.tsx index 80d3e4587f9..c7b6020c269 100644 --- a/src/lib/Scenes/OrderHistory/OrderHistory.tsx +++ b/src/lib/Scenes/OrderHistory/OrderHistory.tsx @@ -14,7 +14,10 @@ import { OrderHistoryRowContainer } from "./OrderHistoryRow" const NUM_ORDERS_TO_FETCH = 10 -export const OrderHistory: React.FC<{ me: OrderHistory_me; relay: RelayPaginationProp }> = ({ relay, me }) => { +export const OrderHistory: React.FC<{ me: OrderHistory_me; relay: RelayPaginationProp }> = ({ + relay, + me, +}) => { const { color } = useTheme() const [isRefreshing, setIsRefreshing] = useState(false) const [isLoadingMore, setIsLoadingMore] = useState(false) @@ -115,7 +118,8 @@ export const OrderHistoryContainer = createPaginationContainer( defaultValue: [APPROVED, CANCELED, FULFILLED, REFUNDED, SUBMITTED] } ) { - orders(first: $count, after: $cursor, states: $states) @connection(key: "OrderHistory_orders") { + orders(first: $count, after: $cursor, states: $states) + @connection(key: "OrderHistory_orders") { edges { node { code @@ -138,7 +142,11 @@ export const OrderHistoryContainer = createPaginationContainer( } }, query: graphql` - query OrderHistoryPaginationQuery($count: Int!, $cursor: String, $states: [CommerceOrderStateEnum!]) { + query OrderHistoryPaginationQuery( + $count: Int! + $cursor: String + $states: [CommerceOrderStateEnum!] + ) { me { ...OrderHistory_me @arguments(count: $count, cursor: $cursor, states: $states) } diff --git a/src/lib/Scenes/OrderHistory/OrderHistoryRow.tests.tsx b/src/lib/Scenes/OrderHistory/OrderHistoryRow.tests.tsx index c1143daa1b2..675ba3ae12a 100644 --- a/src/lib/Scenes/OrderHistory/OrderHistoryRow.tests.tsx +++ b/src/lib/Scenes/OrderHistory/OrderHistoryRow.tests.tsx @@ -68,21 +68,31 @@ describe("Order history row", () => { mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => mockOrder }) expect(extractText(tree.findByProps({ testID: "artist-names" }))).toBe("Torbjørn Rødland") - expect(extractText(tree.findByProps({ testID: "partner-name" }))).toBe("Andrea Festa Fine Art") + expect(extractText(tree.findByProps({ testID: "partner-name" }))).toBe( + "Andrea Festa Fine Art" + ) expect(extractText(tree.findByProps({ testID: "date" }))).toBe("5/18/2021") expect(extractText(tree.findByProps({ testID: "price" }))).toBe("11,200") expect(extractText(tree.findByProps({ testID: "order-status" }))).toBe("pending") expect(extractText(tree.findByProps({ testID: "view-order-button" }))).toContain("View Order") - expect(extractText(tree.findByProps({ testID: "track-package-button" }))).toContain("Track Package") - expect(tree.findByProps({ testID: "image-container" }).findByProps({ testID: "image" })).toBeTruthy() + expect(extractText(tree.findByProps({ testID: "track-package-button" }))).toContain( + "Track Package" + ) + expect( + tree.findByProps({ testID: "image-container" }).findByProps({ testID: "image" }) + ).toBeTruthy() }) describe("Offer mode", () => { it("View Offer button when SUBMITTED state", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...mockOrder, mode: "OFFER" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...mockOrder, mode: "OFFER" }), + }) - expect(extractText(tree.findByProps({ testID: "view-order-button" }))).toContain("View Offer") + expect(extractText(tree.findByProps({ testID: "view-order-button" }))).toContain( + "View Offer" + ) }) it("View Order button when APPROVED state", () => { @@ -91,7 +101,9 @@ describe("Order history row", () => { CommerceOrder: () => ({ ...mockOrder, state: "APPROVED", mode: "OFFER" }), }) - expect(extractText(tree.findByProps({ testID: "view-order-button" }))).toContain("View Order") + expect(extractText(tree.findByProps({ testID: "view-order-button" }))).toContain( + "View Order" + ) }) }) @@ -115,7 +127,9 @@ describe("Order history row", () => { const tree = renderWithWrappers().root mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => order }) - expect(tree.findByProps({ testID: "image-container" }).findByProps({ testID: "image-box" })).toBeTruthy() + expect( + tree.findByProps({ testID: "image-container" }).findByProps({ testID: "image-box" }) + ).toBeTruthy() }) }) @@ -129,21 +143,27 @@ describe("Order history row", () => { it("APPROVED order", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...mockOrder, state: "APPROVED" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...mockOrder, state: "APPROVED" }), + }) expect(extractText(tree.findByProps({ testID: "order-status" }))).toBe("confirmed") }) it("FULFILLED order", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...mockOrder, state: "FULFILLED" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...mockOrder, state: "FULFILLED" }), + }) expect(extractText(tree.findByProps({ testID: "order-status" }))).toBe("delivered") }) it("CANCELED order", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...mockOrder, state: "CANCELED" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...mockOrder, state: "CANCELED" }), + }) expect(extractText(tree.findByProps({ testID: "order-status" }))).toBe("canceled") }) @@ -174,7 +194,9 @@ describe("Order history row", () => { it("REFUNDED order without trackingId", () => { const tree = renderWithWrappers().root - mockEnvironmentPayload(mockEnvironment, { CommerceOrder: () => ({ ...order, state: "REFUNDED" }) }) + mockEnvironmentPayload(mockEnvironment, { + CommerceOrder: () => ({ ...order, state: "REFUNDED" }), + }) expect(extractText(tree.findByProps({ testID: "order-status" }))).toBe("refunded") expect(tree.findByProps({ testID: "view-order-button-box" })).not.toContain(Button) diff --git a/src/lib/Scenes/OrderHistory/OrderHistoryRow.tsx b/src/lib/Scenes/OrderHistory/OrderHistoryRow.tsx index 582d81760f4..4c1f7fd081f 100644 --- a/src/lib/Scenes/OrderHistory/OrderHistoryRow.tsx +++ b/src/lib/Scenes/OrderHistory/OrderHistoryRow.tsx @@ -27,7 +27,11 @@ export const OrderHistoryRow: React.FC = ({ order }) => { {!!artwork?.image ? ( - + ) : ( )} @@ -36,7 +40,13 @@ export const OrderHistoryRow: React.FC = ({ order }) => { {artwork?.artistNames} - + {artwork?.partner?.name} diff --git a/src/lib/Scenes/OrderHistory/SummarySection.tests.tsx b/src/lib/Scenes/OrderHistory/SummarySection.tests.tsx index 53d55b1370f..f45017aebb9 100644 --- a/src/lib/Scenes/OrderHistory/SummarySection.tests.tsx +++ b/src/lib/Scenes/OrderHistory/SummarySection.tests.tsx @@ -70,7 +70,9 @@ describe("SummarySection", () => { }), }) - expect(tree.findByProps({ testID: "shippingTotalLabel" }).props.children).toBe("Second Day Air delivery") + expect(tree.findByProps({ testID: "shippingTotalLabel" }).props.children).toBe( + "Second Day Air delivery" + ) }) it("Render correct shipping name if shipping quote not selected", () => { diff --git a/src/lib/Scenes/Partner/Components/PartnerArtwork.tsx b/src/lib/Scenes/Partner/Components/PartnerArtwork.tsx index 3704d2febdd..f3e50087918 100644 --- a/src/lib/Scenes/Partner/Components/PartnerArtwork.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerArtwork.tsx @@ -1,5 +1,9 @@ import { PartnerArtwork_partner } from "__generated__/PartnerArtwork_partner.graphql" -import { AnimatedArtworkFilterButton, ArtworkFilterNavigator, FilterModalMode } from "lib/Components/ArtworkFilter" +import { + AnimatedArtworkFilterButton, + ArtworkFilterNavigator, + FilterModalMode, +} from "lib/Components/ArtworkFilter" import { useArtworkFilters } from "lib/Components/ArtworkFilter/useArtworkFilters" import { InfiniteScrollArtworksGridContainer as InfiniteScrollArtworksGrid } from "lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid" import { StickyTabPageScrollView } from "lib/Components/StickyTabPage/StickyTabPageScrollView" @@ -30,7 +34,11 @@ export const PartnerArtwork: React.FC<{ {artworks ? ( - + ) : ( )} diff --git a/src/lib/Scenes/Partner/Components/PartnerFollowButton.tsx b/src/lib/Scenes/Partner/Components/PartnerFollowButton.tsx index fb72209807f..fcfd9903c20 100644 --- a/src/lib/Scenes/Partner/Components/PartnerFollowButton.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerFollowButton.tsx @@ -86,7 +86,11 @@ export class PartnerFollowButton extends React.Component { const { partner } = this.props return ( - + ) } } diff --git a/src/lib/Scenes/Partner/Components/PartnerHeader.tsx b/src/lib/Scenes/Partner/Components/PartnerHeader.tsx index 44ec876c4aa..3fa01d3fb33 100644 --- a/src/lib/Scenes/Partner/Components/PartnerHeader.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerHeader.tsx @@ -19,7 +19,9 @@ const PartnerHeader: React.FC<{ {!!eligibleArtworks && ( - {!!eligibleArtworks && formatLargeNumberOfItems(eligibleArtworks, "work", "works")} + + {!!eligibleArtworks && formatLargeNumberOfItems(eligibleArtworks, "work", "works")} + )} {!!partner.profile && ( diff --git a/src/lib/Scenes/Partner/Components/PartnerLocationSection.tsx b/src/lib/Scenes/Partner/Components/PartnerLocationSection.tsx index 52209482796..529b3e9d6ed 100644 --- a/src/lib/Scenes/Partner/Components/PartnerLocationSection.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerLocationSection.tsx @@ -18,7 +18,9 @@ const createLocationsString = (partner: PartnerLocationSection_partner) => { lastUniqCity = uniqCities.pop() } const joinedCities = uniqCities.join(", ") - const locationCountText = `${partner.name} has ${locationsCount} ${cityLength < 2 ? "location" : "locations"} in` + const locationCountText = `${partner.name} has ${locationsCount} ${ + cityLength < 2 ? "location" : "locations" + } in` return { locationText: locationCountText, cityText: joinedCities, lastCity: lastUniqCity } } @@ -54,7 +56,13 @@ class PartnerLocationSection extends React.Component { . - diff --git a/src/lib/Scenes/Partner/Components/PartnerMap.tsx b/src/lib/Scenes/Partner/Components/PartnerMap.tsx index 6c68d1c709c..83becacd9cc 100644 --- a/src/lib/Scenes/Partner/Components/PartnerMap.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerMap.tsx @@ -35,7 +35,11 @@ const PartnerMap: React.FC<{ showActionSheetWithOptions(...tappedOnMap(lat, lng, address, null, null, city, postalCode))} + onPress={() => + showActionSheetWithOptions( + ...tappedOnMap(lat, lng, address, null, null, city, postalCode) + ) + } > { }) }) -const artists: NonNullable["artists"]>["edges"] = [ +const artists: NonNullable< + NonNullable["artists"] +>["edges"] = [ { cursor: "a", id: "a", diff --git a/src/lib/Scenes/Partner/Components/PartnerShowRailItem.tsx b/src/lib/Scenes/Partner/Components/PartnerShowRailItem.tsx index 09ceb679cf3..efe3a10bb11 100644 --- a/src/lib/Scenes/Partner/Components/PartnerShowRailItem.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerShowRailItem.tsx @@ -41,7 +41,10 @@ export class PartnerShowRailItem extends React.Component { return ( this.onPress()}> - + {name} diff --git a/src/lib/Scenes/Partner/Components/PartnerShows.tests.tsx b/src/lib/Scenes/Partner/Components/PartnerShows.tests.tsx index e3ff594a89b..4b084cecbe6 100644 --- a/src/lib/Scenes/Partner/Components/PartnerShows.tests.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerShows.tests.tsx @@ -1,4 +1,7 @@ -import { PartnerShowsTestsQuery, PartnerShowsTestsQueryRawResponse } from "__generated__/PartnerShowsTestsQuery.graphql" +import { + PartnerShowsTestsQuery, + PartnerShowsTestsQueryRawResponse, +} from "__generated__/PartnerShowsTestsQuery.graphql" import { mockEnvironmentPayload } from "lib/tests/mockEnvironmentPayload" import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import { cloneDeep } from "lodash" diff --git a/src/lib/Scenes/Partner/Components/PartnerShows.tsx b/src/lib/Scenes/Partner/Components/PartnerShows.tsx index ba2bfed6e9f..da3382a0b5a 100644 --- a/src/lib/Scenes/Partner/Components/PartnerShows.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerShows.tsx @@ -19,7 +19,9 @@ import { PartnerShowsRailContainer as PartnerShowsRail } from "./PartnerShowsRai const PAGE_SIZE = 32 interface ShowGridItemProps { - show: NonNullable["edges"]>[0]>["node"]> + show: NonNullable< + NonNullable["edges"]>[0]>["node"] + > itemIndex: number } @@ -36,13 +38,18 @@ class ShowGridItem extends React.Component { return ( {({ space }) => { - const styles = itemIndex % 2 === 0 ? { paddingRight: space(1) } : { paddingLeft: space(1) } + const styles = + itemIndex % 2 === 0 ? { paddingRight: space(1) } : { paddingLeft: space(1) } return ( {showImageURL ? ( - + ) : ( )} @@ -122,7 +129,9 @@ export const PartnerShows: React.FC<{ // using tabIsActive here to render only the minimal UI on this tab before the user actually switches to it onEndReachedThreshold={tabIsActive ? 1 : 0} // render up to the first chunk on initial mount - initialNumToRender={sections.findIndex((section) => section.key.startsWith("chunk")) + 1} + initialNumToRender={ + sections.findIndex((section) => section.key.startsWith("chunk")) + 1 + } windowSize={tabIsActive ? 5 : 1} onEndReached={() => { if (isLoadingMore || !relay.hasMore()) { @@ -169,8 +178,12 @@ export const PartnerShowsFragmentContainer = createPaginationContainer( } } } - pastShows: showsConnection(status: CLOSED, sort: END_AT_DESC, first: $count, after: $cursor) - @connection(key: "Partner_pastShows") { + pastShows: showsConnection( + status: CLOSED + sort: END_AT_DESC + first: $count + after: $cursor + ) @connection(key: "Partner_pastShows") { pageInfo { hasNextPage startCursor diff --git a/src/lib/Scenes/Partner/Components/PartnerShowsRail.tsx b/src/lib/Scenes/Partner/Components/PartnerShowsRail.tsx index 09a1276a8dc..cdd1ecae1f8 100644 --- a/src/lib/Scenes/Partner/Components/PartnerShowsRail.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerShowsRail.tsx @@ -14,7 +14,9 @@ const PartnerShowsRail: React.FC<{ relay: RelayPaginationProp }> = ({ partner, relay }) => { const [fetchingNextPage, setFetchingNextPage] = useState(false) - const currentAndUpcomingShows = extractNodes(partner.currentAndUpcomingShows).filter((show) => show.isDisplayable) + const currentAndUpcomingShows = extractNodes(partner.currentAndUpcomingShows).filter( + (show) => show.isDisplayable + ) const fetchNextPage = () => { if (fetchingNextPage) { @@ -59,8 +61,12 @@ export const PartnerShowsRailContainer = createPaginationContainer( fragment PartnerShowsRail_partner on Partner @argumentDefinitions(count: { type: "Int", defaultValue: 6 }, cursor: { type: "String" }) { internalID - currentAndUpcomingShows: showsConnection(status: CURRENT, sort: END_AT_ASC, first: $count, after: $cursor) - @connection(key: "Partner_currentAndUpcomingShows") { + currentAndUpcomingShows: showsConnection( + status: CURRENT + sort: END_AT_ASC + first: $count + after: $cursor + ) @connection(key: "Partner_currentAndUpcomingShows") { pageInfo { hasNextPage startCursor diff --git a/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tests.tsx b/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tests.tsx index 408781a935c..5cfb9272b15 100644 --- a/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tests.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tests.tsx @@ -12,15 +12,21 @@ describe("CustomPriceInput", () => { } it("correctly displays title when gallery has fair partnership", () => { - const { findByText } = renderWithWrappersTL() + const { findByText } = renderWithWrappersTL( + + ) expect( - findByText("Cool Gallery participated in Artsy’s art fair coverage but does not have a full profile.") + findByText( + "Cool Gallery participated in Artsy’s art fair coverage but does not have a full profile." + ) ).toBeTruthy() }) it("correctly displays title when gallery does not have fair partnership", () => { const { findByText } = renderWithWrappersTL() - expect(findByText("Cool Gallery is not currently an Artsy partner and does not have a full profile.")).toBeTruthy() + expect( + findByText("Cool Gallery is not currently an Artsy partner and does not have a full profile.") + ).toBeTruthy() }) it(`displays "Are you a representative of Cool Gallery?"`, () => { diff --git a/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tsx b/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tsx index 4f66236975f..e54b4ff01cd 100644 --- a/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tsx +++ b/src/lib/Scenes/Partner/Components/PartnerSubscriberBanner.tsx @@ -31,11 +31,14 @@ export const PartnerSubscriberBanner: React.FC = ( ) } -export const PartnerSubscriberBannerFragmentContainer = createFragmentContainer(PartnerSubscriberBanner, { - partner: graphql` - fragment PartnerSubscriberBanner_partner on Partner { - name - hasFairPartnership - } - `, -}) +export const PartnerSubscriberBannerFragmentContainer = createFragmentContainer( + PartnerSubscriberBanner, + { + partner: graphql` + fragment PartnerSubscriberBanner_partner on Partner { + name + hasFairPartnership + } + `, + } +) diff --git a/src/lib/Scenes/Partner/Screens/PartnerLocations.tests.tsx b/src/lib/Scenes/Partner/Screens/PartnerLocations.tests.tsx index eb4a5371a1e..6a237e4403d 100644 --- a/src/lib/Scenes/Partner/Screens/PartnerLocations.tests.tsx +++ b/src/lib/Scenes/Partner/Screens/PartnerLocations.tests.tsx @@ -12,7 +12,11 @@ describe("PartnerLocations", () => { await renderRelayTree({ Component: (props: any) => { return ( - + ) }, query: graphql` diff --git a/src/lib/Scenes/Partner/Screens/PartnerLocations.tsx b/src/lib/Scenes/Partner/Screens/PartnerLocations.tsx index 02f12ffd910..a987b5e7dc3 100644 --- a/src/lib/Scenes/Partner/Screens/PartnerLocations.tsx +++ b/src/lib/Scenes/Partner/Screens/PartnerLocations.tsx @@ -59,7 +59,8 @@ export const PartnerLocationsContainer = createPaginationContainer( @argumentDefinitions(count: { type: "Int", defaultValue: 4 }, cursor: { type: "String" }) { name internalID - locations: locationsConnection(first: $count, after: $cursor) @connection(key: "Partner_locations") { + locations: locationsConnection(first: $count, after: $cursor) + @connection(key: "Partner_locations") { pageInfo { hasNextPage startCursor diff --git a/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tests.tsx b/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tests.tsx index 27e713f066e..dceeb3d79ea 100644 --- a/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tests.tsx +++ b/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tests.tsx @@ -21,10 +21,9 @@ describe(PrivacyRequest, () => { tree.find(LinkText).at(1).simulate("press") - expect(LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithSubject).toHaveBeenCalledWith( - "Personal Data Request", - "privacy@artsy.net" - ) + expect( + LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithSubject + ).toHaveBeenCalledWith("Personal Data Request", "privacy@artsy.net") }) it("handles CCPA button presses", () => { @@ -32,7 +31,9 @@ describe(PrivacyRequest, () => { tree.find(Button).simulate("press") - expect(LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithBody).toHaveBeenCalledWith( + expect( + LegacyNativeModules.ARScreenPresenterModule.presentEmailComposerWithBody + ).toHaveBeenCalledWith( "Hello, I'm contacting you to ask that...", "Personal Data Request", "privacy@artsy.net" diff --git a/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tsx b/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tsx index 7ae501162de..85c98f33628 100644 --- a/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tsx +++ b/src/lib/Scenes/PrivacyRequest/PrivacyRequest.tsx @@ -22,12 +22,17 @@ export class PrivacyRequest extends React.Component { }> Please see Artsy’s{" "} - navigate("/privacy", { modal: true })}>Privacy Policy for more - information about the information we collect, how we use it, and why we use it. + navigate("/privacy", { modal: true })}> + Privacy Policy + {" "} + for more information about the information we collect, how we use it, and why we use + it. To submit a personal data request tap the button below or email{" "} - presentEmailComposer("privacy@artsy.net", "Personal Data Request")}> + presentEmailComposer("privacy@artsy.net", "Personal Data Request")} + > privacy@artsy.net. {" "} diff --git a/src/lib/Scenes/Sale/BuyNowArtworksRail.tests.tsx b/src/lib/Scenes/Sale/BuyNowArtworksRail.tests.tsx index 42c7628a5d2..e50d07bd1ab 100644 --- a/src/lib/Scenes/Sale/BuyNowArtworksRail.tests.tsx +++ b/src/lib/Scenes/Sale/BuyNowArtworksRail.tests.tsx @@ -4,7 +4,10 @@ import { renderWithWrappersTL } from "lib/tests/renderWithWrappers" import React from "react" import { graphql, QueryRenderer } from "react-relay" import { createMockEnvironment } from "relay-test-utils" -import { BuyNowArtworksRailContainer, INITIAL_NUMBER_TO_RENDER } from "./Components/BuyNowArtworksRail" +import { + BuyNowArtworksRailContainer, + INITIAL_NUMBER_TO_RENDER, +} from "./Components/BuyNowArtworksRail" jest.unmock("react-relay") diff --git a/src/lib/Scenes/Sale/Components/BuyNowArtworksRail.tsx b/src/lib/Scenes/Sale/Components/BuyNowArtworksRail.tsx index 07bbe3e63e9..879b32b1e44 100644 --- a/src/lib/Scenes/Sale/Components/BuyNowArtworksRail.tsx +++ b/src/lib/Scenes/Sale/Components/BuyNowArtworksRail.tsx @@ -82,7 +82,8 @@ export const BuyNowArtworksRailContainer = createPaginationContainer( @argumentDefinitions(count: { type: "Int", defaultValue: 4 }, cursor: { type: "String" }) { internalID promotedSale { - saleArtworksConnection(first: $count, after: $cursor) @connection(key: "Sale_saleArtworksConnection") { + saleArtworksConnection(first: $count, after: $cursor) + @connection(key: "Sale_saleArtworksConnection") { edges { node { artwork { diff --git a/src/lib/Scenes/Sale/Components/RegisterToBidButton.tsx b/src/lib/Scenes/Sale/Components/RegisterToBidButton.tsx index 76cb25edb1a..3afcb33ddff 100644 --- a/src/lib/Scenes/Sale/Components/RegisterToBidButton.tsx +++ b/src/lib/Scenes/Sale/Components/RegisterToBidButton.tsx @@ -1,4 +1,9 @@ -import { ContextModule, ScreenOwnerType, tappedRegisterToBid, TappedRegisterToBidArgs } from "@artsy/cohesion" +import { + ContextModule, + ScreenOwnerType, + tappedRegisterToBid, + TappedRegisterToBidArgs, +} from "@artsy/cohesion" import { RegisterToBidButton_me } from "__generated__/RegisterToBidButton_me.graphql" import { RegisterToBidButton_sale } from "__generated__/RegisterToBidButton_sale.graphql" import { Box, Button, CheckIcon, Flex, Spacer, Text } from "palette" @@ -14,7 +19,12 @@ interface RegisterToBidButtonProps { contextModule: ContextModule } -const RegisterToBidButton: React.FC = ({ me, sale, contextType, contextModule }) => { +const RegisterToBidButton: React.FC = ({ + me, + sale, + contextType, + contextModule, +}) => { const { trackEvent } = useTracking() if (sale.registrationStatus === null) { diff --git a/src/lib/Scenes/Sale/Components/SaleActiveBidItem.tsx b/src/lib/Scenes/Sale/Components/SaleActiveBidItem.tsx index d5a0dcedd21..2e156278639 100644 --- a/src/lib/Scenes/Sale/Components/SaleActiveBidItem.tsx +++ b/src/lib/Scenes/Sale/Components/SaleActiveBidItem.tsx @@ -23,7 +23,9 @@ export const SaleActiveBidItem: React.FC = ({ lotStandin return ( saleArtwork && ( lotStanding?.saleArtwork?.artwork?.href && navigate(lotStanding.saleArtwork.artwork.href)} + onPress={() => + lotStanding?.saleArtwork?.artwork?.href && navigate(lotStanding.saleArtwork.artwork.href) + } > diff --git a/src/lib/Scenes/Sale/Components/SaleArtworkList.tsx b/src/lib/Scenes/Sale/Components/SaleArtworkList.tsx index 1a548f02403..a81539b6538 100644 --- a/src/lib/Scenes/Sale/Components/SaleArtworkList.tsx +++ b/src/lib/Scenes/Sale/Components/SaleArtworkList.tsx @@ -49,9 +49,15 @@ export const SaleArtworkList: React.FC = ({ data={artworks} onEndReached={loadMoreArtworks} ItemSeparatorComponent={() => } - ListFooterComponent={loadingMoreData ? : null} + ListFooterComponent={ + loadingMoreData ? : null + } renderItem={({ item }) => ( - + )} keyExtractor={(item) => item.id!} style={{ paddingHorizontal: 20 }} diff --git a/src/lib/Scenes/Sale/Components/SaleArtworkListItem.tsx b/src/lib/Scenes/Sale/Components/SaleArtworkListItem.tsx index 227539d57e4..45cccc6274f 100644 --- a/src/lib/Scenes/Sale/Components/SaleArtworkListItem.tsx +++ b/src/lib/Scenes/Sale/Components/SaleArtworkListItem.tsx @@ -1,4 +1,10 @@ -import { ContextModule, OwnerType, ScreenOwnerType, tappedEntityGroup, TappedEntityGroupArgs } from "@artsy/cohesion" +import { + ContextModule, + OwnerType, + ScreenOwnerType, + tappedEntityGroup, + TappedEntityGroupArgs, +} from "@artsy/cohesion" import { SaleArtworkListItem_artwork } from "__generated__/SaleArtworkListItem_artwork.graphql" import { saleMessageOrBidInfo } from "lib/Components/ArtworkGrids/ArtworkGridItem" import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView" @@ -46,13 +52,22 @@ export const SaleArtworkListItem: React.FC = ({ artwork, contextScreenOwn artwork, }) - const imageDimensions = getImageDimensions(artwork.image?.height, artwork.image?.width, CONTAINER_HEIGHT) + const imageDimensions = getImageDimensions( + artwork.image?.height, + artwork.image?.width, + CONTAINER_HEIGHT + ) return ( {!!artwork.image && ( - + = ({ me }) => { export const SaleArtworksRailContainer = createFragmentContainer(SaleArtworksRail, { me: graphql` fragment SaleArtworksRail_me on Me @argumentDefinitions(saleID: { type: "ID" }) { - lotsByFollowedArtistsConnection(first: 10, includeArtworksByFollowedArtists: true, saleID: $saleID) { + lotsByFollowedArtistsConnection( + first: 10 + includeArtworksByFollowedArtists: true + saleID: $saleID + ) { edges { node { id diff --git a/src/lib/Scenes/Sale/Components/SaleHeader.tsx b/src/lib/Scenes/Sale/Components/SaleHeader.tsx index a06419a92c3..5579f6d0d16 100644 --- a/src/lib/Scenes/Sale/Components/SaleHeader.tsx +++ b/src/lib/Scenes/Sale/Components/SaleHeader.tsx @@ -76,7 +76,9 @@ export const SaleHeader: React.FC = ({ sale, scrollAnim }) => { diff --git a/src/lib/Scenes/Sale/Components/SaleLotsList.tsx b/src/lib/Scenes/Sale/Components/SaleLotsList.tsx index e277f65a258..8e410cddbef 100644 --- a/src/lib/Scenes/Sale/Components/SaleLotsList.tsx +++ b/src/lib/Scenes/Sale/Components/SaleLotsList.tsx @@ -40,7 +40,9 @@ export const SaleLotsListSortMode = ({ totalCount: number | null | undefined }) => { const getSortDescription = useCallback(() => { - const sortMode = ORDERED_SALE_ARTWORK_SORTS.find((sort) => sort.paramValue === filterParams?.sort) + const sortMode = ORDERED_SALE_ARTWORK_SORTS.find( + (sort) => sort.paramValue === filterParams?.sort + ) if (sortMode) { return sortMode.displayText } @@ -72,11 +74,17 @@ export const SaleLotsList: React.FC = ({ const appliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) const filterTypeState = ArtworksFiltersStore.useStoreState((state) => state.filterType) - const setFiltersCountAction = ArtworksFiltersStore.useStoreActions((action) => action.setFiltersCountAction) - const setFilterTypeAction = ArtworksFiltersStore.useStoreActions((action) => action.setFilterTypeAction) + const setFiltersCountAction = ArtworksFiltersStore.useStoreActions( + (action) => action.setFiltersCountAction + ) + const setFilterTypeAction = ArtworksFiltersStore.useStoreActions( + (action) => action.setFilterTypeAction + ) const filterParams = filterArtworksParams(appliedFiltersState, filterTypeState) - const viewAsFilter = appliedFiltersState.find((filter) => filter.paramName === FilterParamName.viewAs) + const viewAsFilter = appliedFiltersState.find( + (filter) => filter.paramName === FilterParamName.viewAs + ) const counts = saleArtworksConnection.saleArtworksConnection?.counts // Add the new medium to geneIDs array @@ -134,7 +142,11 @@ export const SaleLotsList: React.FC = ({ return ( - + {viewAsFilter?.paramValue === ViewAsValues.List ? ( = ({ sale, me, below, relay }) => { } const scrollToTop = () => { - const saleLotsListIndex = saleSectionsData.findIndex((section) => section.key === SALE_LOTS_LIST) + const saleLotsListIndex = saleSectionsData.findIndex( + (section) => section.key === SALE_LOTS_LIST + ) flatListRef.current?.scrollToIndex({ index: saleLotsListIndex, viewOffset: 50 }) } @@ -228,7 +234,10 @@ export const Sale: React.FC = ({ sale, me, below, relay }) => { exitModal={closeFilterArtworksModal} closeModal={closeFilterArtworksModal} /> - + ) @@ -348,10 +357,10 @@ export const SaleScreenQuery = graphql` } ` -export const SaleQueryRenderer: React.FC<{ saleID: string; environment?: RelayModernEnvironment }> = ({ - saleID, - environment, -}) => { +export const SaleQueryRenderer: React.FC<{ + saleID: string + environment?: RelayModernEnvironment +}> = ({ saleID, environment }) => { const { trackEvent } = useTracking() useEffect(() => { @@ -373,7 +382,10 @@ export const SaleQueryRenderer: React.FC<{ saleID: string; environment?: RelayMo # query SaleBelowTheFoldQuery($saleID: String!, $saleSlug: ID!) { query SaleBelowTheFoldQuery($saleID: ID) { ...SaleLotsList_saleArtworksConnection @arguments(saleID: $saleID) - unfilteredSaleArtworksConnection: saleArtworksConnection(saleID: $saleID, aggregations: [TOTAL]) { + unfilteredSaleArtworksConnection: saleArtworksConnection( + saleID: $saleID + aggregations: [TOTAL] + ) { ...SaleLotsList_unfilteredSaleArtworksConnection counts { total @@ -395,7 +407,9 @@ export const SaleQueryRenderer: React.FC<{ saleID: string; environment?: RelayMo if (!props?.above.me || !props.above.sale) { return } - return + return ( + + ) }} cacheConfig={{ // Bypass Relay cache on retries. diff --git a/src/lib/Scenes/Sale/SaleActiveBidItem.tests.tsx b/src/lib/Scenes/Sale/SaleActiveBidItem.tests.tsx index fe53dabb4ed..f9dbddf7d61 100644 --- a/src/lib/Scenes/Sale/SaleActiveBidItem.tests.tsx +++ b/src/lib/Scenes/Sale/SaleActiveBidItem.tests.tsx @@ -58,7 +58,11 @@ describe("SaleActiveBidItem", () => { `} variables={{}} render={({ props }) => { - if (props?.me?.lotStandings && Array.isArray(props.me.lotStandings) && props.me.lotStandings[0]) { + if ( + props?.me?.lotStandings && + Array.isArray(props.me.lotStandings) && + props.me.lotStandings[0] + ) { return } return null diff --git a/src/lib/Scenes/Sale/SaleArtworksRail.tests.tsx b/src/lib/Scenes/Sale/SaleArtworksRail.tests.tsx index 85b25221f7e..ee7948c0c1a 100644 --- a/src/lib/Scenes/Sale/SaleArtworksRail.tests.tsx +++ b/src/lib/Scenes/Sale/SaleArtworksRail.tests.tsx @@ -43,8 +43,12 @@ describe("SaleArtworksRail", () => { mockEnvironmentPayload(mockEnvironment, mockProps) - expect(tree.root.findAllByType(SectionTitle)[0].props.title).toEqual("Lots by artists you follow") - expect(tree.root.findAllByType(SaleArtworkTileRailCardContainer)).toHaveLength(INITIAL_NUMBER_TO_RENDER) + expect(tree.root.findAllByType(SectionTitle)[0].props.title).toEqual( + "Lots by artists you follow" + ) + expect(tree.root.findAllByType(SaleArtworkTileRailCardContainer)).toHaveLength( + INITIAL_NUMBER_TO_RENDER + ) }) it("returns null if there are no artworks", () => { diff --git a/src/lib/Scenes/Sale/SaleHeader.tests.tsx b/src/lib/Scenes/Sale/SaleHeader.tests.tsx index 1eec4e5d7b6..bab81323d79 100644 --- a/src/lib/Scenes/Sale/SaleHeader.tests.tsx +++ b/src/lib/Scenes/Sale/SaleHeader.tests.tsx @@ -80,7 +80,9 @@ describe("SaleHeader", () => { }) ) - expect(extractText(tree.root.findByProps({ testID: "sale-header-hero" }))).toBe("Auction closed") + expect(extractText(tree.root.findByProps({ testID: "sale-header-hero" }))).toBe( + "Auction closed" + ) }) it("does not render auction is closed when an auction is still active", () => { diff --git a/src/lib/Scenes/Sale/SaleLotsList.tests.tsx b/src/lib/Scenes/Sale/SaleLotsList.tests.tsx index 35dbe503c6a..c4326b1600b 100644 --- a/src/lib/Scenes/Sale/SaleLotsList.tests.tsx +++ b/src/lib/Scenes/Sale/SaleLotsList.tests.tsx @@ -1,7 +1,10 @@ import { SaleLotsListTestsQuery } from "__generated__/SaleLotsListTestsQuery.graphql" import { FilterParamName, ViewAsValues } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { FilterParams } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { InfiniteScrollArtworksGridContainer } from "lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid" import { extractText } from "lib/tests/extractText" import { mockEnvironmentPayload } from "lib/tests/mockEnvironmentPayload" @@ -10,7 +13,12 @@ import React from "react" import { graphql, QueryRenderer } from "react-relay" import { createMockEnvironment } from "relay-test-utils" import { SaleArtworkListContainer } from "./Components/SaleArtworkList" -import { FilterDescription, FilterTitle, SaleLotsListContainer, SaleLotsListSortMode } from "./Components/SaleLotsList" +import { + FilterDescription, + FilterTitle, + SaleLotsListContainer, + SaleLotsListSortMode, +} from "./Components/SaleLotsList" jest.unmock("react-relay") diff --git a/src/lib/Scenes/Sale/helpers.tests.ts b/src/lib/Scenes/Sale/helpers.tests.ts index 764b1701d84..439801225ec 100644 --- a/src/lib/Scenes/Sale/helpers.tests.ts +++ b/src/lib/Scenes/Sale/helpers.tests.ts @@ -2,17 +2,25 @@ import moment from "moment" import { saleStatus } from "./helpers" -const dAdd = (date: number, amount: number, type: "day" | "days") => moment(date).add(amount, type).toISOString() -const dSub = (date: number, amount: number, type: "day" | "days") => moment(date).subtract(amount, type).toISOString() +const dAdd = (date: number, amount: number, type: "day" | "days") => + moment(date).add(amount, type).toISOString() +const dSub = (date: number, amount: number, type: "day" | "days") => + moment(date).subtract(amount, type).toISOString() describe(saleStatus, () => { it("returns the right sale status", () => { const now = Date.now() - expect(saleStatus(dAdd(now, 1, "day"), dAdd(now, 2, "days"), dAdd(now, 1, "day"))).toBe("notYetOpen") + expect(saleStatus(dAdd(now, 1, "day"), dAdd(now, 2, "days"), dAdd(now, 1, "day"))).toBe( + "notYetOpen" + ) expect(saleStatus(dAdd(now, 1, "day"), dAdd(now, 2, "days"), null)).toBe("notYetOpen") - expect(saleStatus(dSub(now, 1, "day"), dAdd(now, 2, "days"), dAdd(now, 1, "day"))).toBe("active") + expect(saleStatus(dSub(now, 1, "day"), dAdd(now, 2, "days"), dAdd(now, 1, "day"))).toBe( + "active" + ) expect(saleStatus(dSub(now, 1, "day"), dAdd(now, 2, "days"), null)).toBe("active") - expect(saleStatus(dSub(now, 3, "days"), dAdd(now, 2, "days"), dSub(now, 1, "day"))).toBe("closed") + expect(saleStatus(dSub(now, 3, "days"), dAdd(now, 2, "days"), dSub(now, 1, "day"))).toBe( + "closed" + ) expect(saleStatus(dSub(now, 3, "days"), dSub(now, 2, "days"), null)).toBe("closed") }) }) diff --git a/src/lib/Scenes/SaleInfo/SaleInfo.tests.tsx b/src/lib/Scenes/SaleInfo/SaleInfo.tests.tsx index 5cfcaab37a4..2de576b7a1d 100644 --- a/src/lib/Scenes/SaleInfo/SaleInfo.tests.tsx +++ b/src/lib/Scenes/SaleInfo/SaleInfo.tests.tsx @@ -128,11 +128,15 @@ describe("SaleInfo", () => { }) ) - expect(extractText(tree.root)).toContain("On the hammer price up to and including $150,000: 25%") + expect(extractText(tree.root)).toContain( + "On the hammer price up to and including $150,000: 25%" + ) expect(extractText(tree.root)).toContain( "On the hammer price in excess of $150,000 up to and including $3,000,000: 20%" ) - expect(extractText(tree.root)).toContain("On the portion of the hammer price in excess of $3,000,000: 12%") + expect(extractText(tree.root)).toContain( + "On the portion of the hammer price in excess of $3,000,000: 12%" + ) }) }) diff --git a/src/lib/Scenes/SaleInfo/SaleInfo.tsx b/src/lib/Scenes/SaleInfo/SaleInfo.tsx index 30eb8bce871..b01fe733324 100644 --- a/src/lib/Scenes/SaleInfo/SaleInfo.tsx +++ b/src/lib/Scenes/SaleInfo/SaleInfo.tsx @@ -55,9 +55,9 @@ const AuctionIsLive = () => ( This is a live auction - Participating in a live auction means you’ll be competing against bidders in real time on an auction room floor. - You can place max bids which will be represented by Artsy in the auction room or you can bid live when the auction - opens. + Participating in a live auction means you’ll be competing against bidders in real time on an + auction room floor. You can place max bids which will be represented by Artsy in the auction + room or you can bid live when the auction opens. ) @@ -182,7 +182,9 @@ const BuyersPremium: React.FC<{ sale: SaleInfo_sale }> = (props) => { } if (buyersPremium.length === 1) { - premiumDisplay = {makePercent(buyersPremium[0]?.percent || 0)}% on the hammer price + premiumDisplay = ( + {makePercent(buyersPremium[0]?.percent || 0)}% on the hammer price + ) } else { premiumDisplay = createPremiumDisplay(props) } @@ -264,7 +266,10 @@ export const SaleInfoQueryRenderer: React.FC<{ saleID: string }> = ({ saleID: sa } `} variables={{ saleID }} - render={renderWithPlaceholder({ Container: SaleInfoContainer, renderPlaceholder: SaleInfoPlaceholder })} + render={renderWithPlaceholder({ + Container: SaleInfoContainer, + renderPlaceholder: SaleInfoPlaceholder, + })} /> ) } diff --git a/src/lib/Scenes/Sales/Components/SaleList.tsx b/src/lib/Scenes/Sales/Components/SaleList.tsx index 4a6ae498168..b5ee367abe8 100644 --- a/src/lib/Scenes/Sales/Components/SaleList.tsx +++ b/src/lib/Scenes/Sales/Components/SaleList.tsx @@ -8,10 +8,10 @@ import { useScreenDimensions } from "lib/utils/useScreenDimensions" import { FragmentRef } from "react-relay" import SaleListItem from "./SaleListItem" -export const SaleList: React.FC<{ sales: Array>; title: string }> = ({ - sales, - title, -}) => { +export const SaleList: React.FC<{ + sales: Array> + title: string +}> = ({ sales, title }) => { const { width } = useScreenDimensions() const isIPad = width > 700 const columnCount = isIPad ? 4 : 2 @@ -32,7 +32,13 @@ export const SaleList: React.FC<{ sales: Array>; }} > {sales.map((sale, index) => ( - + ))} diff --git a/src/lib/Scenes/Sales/Components/SaleListItem.tests.tsx b/src/lib/Scenes/Sales/Components/SaleListItem.tests.tsx index 33119552be2..7e32f3dcd59 100644 --- a/src/lib/Scenes/Sales/Components/SaleListItem.tests.tsx +++ b/src/lib/Scenes/Sales/Components/SaleListItem.tests.tsx @@ -6,7 +6,9 @@ import { renderWithWrappers } from "lib/tests/renderWithWrappers" import SaleListItem from "./SaleListItem" it("renders without throwing an error", () => { - renderWithWrappers() + renderWithWrappers( + + ) }) const props = { diff --git a/src/lib/Scenes/Sales/index.tests.tsx b/src/lib/Scenes/Sales/index.tests.tsx index 0f4170ca25f..251d5378453 100644 --- a/src/lib/Scenes/Sales/index.tests.tsx +++ b/src/lib/Scenes/Sales/index.tests.tsx @@ -12,8 +12,10 @@ import { SalesFragmentContainer } from "./index" jest.mock("lib/Components/LotsByArtistsYouFollowRail/LotsByFollowedArtistsRail.tsx", () => "") it("renders the ZeroState when there are no sales", () => { - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const auctions = shallow() + const auctions = shallow( + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + + ) expect(auctions.find("ZeroState").length).toEqual(1) }) diff --git a/src/lib/Scenes/Sales/index.tsx b/src/lib/Scenes/Sales/index.tsx index 33614cb14c6..0d959468c2d 100644 --- a/src/lib/Scenes/Sales/index.tsx +++ b/src/lib/Scenes/Sales/index.tsx @@ -57,13 +57,20 @@ class Sales extends React.Component { const timedAuctions = sales.filter((a) => !a.live_start_at) return ( - + } + refreshControl={ + + } > - + diff --git a/src/lib/Scenes/SavedAddresses/SavedAddresses.tests.tsx b/src/lib/Scenes/SavedAddresses/SavedAddresses.tests.tsx index 135b5b02051..60b9c9ca28a 100644 --- a/src/lib/Scenes/SavedAddresses/SavedAddresses.tests.tsx +++ b/src/lib/Scenes/SavedAddresses/SavedAddresses.tests.tsx @@ -123,7 +123,9 @@ describe(SavedAddressesQueryRenderer, () => { }) fireEvent.press(getAllByText("Add New Address")[0]) - expect(navigate).toHaveBeenCalledWith("/my-profile/saved-addresses/new-address", { modal: true }) + expect(navigate).toHaveBeenCalledWith("/my-profile/saved-addresses/new-address", { + modal: true, + }) }) it("should navigate to edit address screen", () => { @@ -231,7 +233,9 @@ describe(SavedAddressesQueryRenderer, () => { act(() => fireEvent.press(getAllByText("Delete")[0])) const createOperation = mockEnvironment.mock.getMostRecentOperation() - expect(createOperation.request.node.operation.name).toEqual("deleteSavedAddressDeleteUserAddressMutation") + expect(createOperation.request.node.operation.name).toEqual( + "deleteSavedAddressDeleteUserAddressMutation" + ) expect(createOperation.request.variables).toEqual({ input: { userAddressID: "5840" } }) }) }) diff --git a/src/lib/Scenes/SavedAddresses/SavedAddresses.tsx b/src/lib/Scenes/SavedAddresses/SavedAddresses.tsx index 091807d4518..c8701105ef3 100644 --- a/src/lib/Scenes/SavedAddresses/SavedAddresses.tsx +++ b/src/lib/Scenes/SavedAddresses/SavedAddresses.tsx @@ -25,7 +25,8 @@ interface CardProps { const Card = styled(Flex)` border: 1px solid - ${(props: CardProps) => (props.isDefault ? themeGet("colors.black100") : themeGet("colors.black30"))}; + ${(props: CardProps) => + props.isDefault ? themeGet("colors.black100") : themeGet("colors.black30")}; border-radius: 4; ` @@ -35,7 +36,10 @@ const NUM_ADDRESSES_TO_FETCH = 10 // tslint:disable-next-line:no-empty export const util = { onRefresh: () => {} } -const SavedAddresses: React.FC<{ me: SavedAddresses_me; relay: RelayRefetchProp }> = ({ me, relay }) => { +const SavedAddresses: React.FC<{ me: SavedAddresses_me; relay: RelayRefetchProp }> = ({ + me, + relay, +}) => { const [isRefreshing, setIsRefreshing] = useState(false) const toast = useToast() @@ -103,7 +107,9 @@ const SavedAddresses: React.FC<{ me: SavedAddresses_me; relay: RelayRefetchProp {item.name} - {[item.addressLine1, item?.addressLine2, item?.addressLine3].filter(Boolean).join(", ")} + {[item.addressLine1, item?.addressLine2, item?.addressLine3] + .filter(Boolean) + .join(", ")} {item.city}, {item.postalCode} @@ -122,7 +128,11 @@ const SavedAddresses: React.FC<{ me: SavedAddresses_me; relay: RelayRefetchProp testID={`EditAddress-${item.internalID}`} onPress={() => onPressEditAddress(item.internalID)} > - + Edit @@ -145,7 +155,9 @@ const SavedAddresses: React.FC<{ me: SavedAddresses_me; relay: RelayRefetchProp navigate("/my-profile/saved-addresses/new-address", { modal: true })} + handleOnPress={() => + navigate("/my-profile/saved-addresses/new-address", { modal: true }) + } title="Add New Address" /> @@ -162,7 +174,9 @@ const SavedAddresses: React.FC<{ me: SavedAddresses_me; relay: RelayRefetchProp Please add an address for a faster checkout experience in the future. navigate("/my-profile/saved-addresses/new-address", { modal: true })} + handleOnPress={() => + navigate("/my-profile/saved-addresses/new-address", { modal: true }) + } title="Add New Address" /> diff --git a/src/lib/Scenes/SavedAddresses/SavedAddressesForm.tsx b/src/lib/Scenes/SavedAddresses/SavedAddressesForm.tsx index 906ed7b1f58..ff21fbe4560 100644 --- a/src/lib/Scenes/SavedAddresses/SavedAddressesForm.tsx +++ b/src/lib/Scenes/SavedAddresses/SavedAddressesForm.tsx @@ -78,11 +78,16 @@ const useStore = createComponentStore({ region: emptyFieldState(), }, allPresent: computed((store) => { - return Boolean(Object.keys(store.fields).every((k) => store.fields[k as keyof FormFields].isPresent)) + return Boolean( + Object.keys(store.fields).every((k) => store.fields[k as keyof FormFields].isPresent) + ) }), }) -export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId?: string }> = ({ me, addressId }) => { +export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId?: string }> = ({ + me, + addressId, +}) => { const isEditForm = !!addressId const toast = useToast() const [isValidNumber, setIsValidNumber] = useState(false) @@ -108,7 +113,8 @@ export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId const screenRef = useRef(null) const submitAddAddress = async () => { - const phoneNumberCountryCode = countryCodes[cleanUserPhoneNumber(phoneNumber)?.countryCode?.toLocaleUpperCase()] + const phoneNumberCountryCode = + countryCodes[cleanUserPhoneNumber(phoneNumber)?.countryCode?.toLocaleUpperCase()] try { const creatingResponse = await createUserAddress({ @@ -124,7 +130,9 @@ export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId }) if (isDefaultAddress) { - await setAsDefaultAddress(creatingResponse.createUserAddress?.userAddressOrErrors.internalID!) + await setAsDefaultAddress( + creatingResponse.createUserAddress?.userAddressOrErrors.internalID! + ) } if (!creatingResponse.createUserAddress?.userAddressOrErrors.errors) { toast.show("Address successfully added", "top") @@ -132,12 +140,15 @@ export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId goBack() } catch (e: any) { captureMessage(e.stack) - Alert.alert("Something went wrong while attempting to save your address. Please try again or contact us.") + Alert.alert( + "Something went wrong while attempting to save your address. Please try again or contact us." + ) } } const editUserAddress = async (userAddressID: string) => { - const phoneNumberCountryCode = countryCodes[cleanUserPhoneNumber(phoneNumber)?.countryCode?.toLocaleUpperCase()] + const phoneNumberCountryCode = + countryCodes[cleanUserPhoneNumber(phoneNumber)?.countryCode?.toLocaleUpperCase()] try { const response = await updateUserAddress(userAddressID, { @@ -160,7 +171,9 @@ export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId } goBack() } catch (e: any) { - Alert.alert("Something went wrong while attempting to save your address. Please try again or contact us.") + Alert.alert( + "Something went wrong while attempting to save your address. Please try again or contact us." + ) captureMessage(e.stack) } } @@ -190,7 +203,10 @@ export const SavedAddressesForm: React.FC<{ me: SavedAddressesForm_me; addressId value={state.fields.name.value ?? ""} onChangeText={actions.fields.name.setValue} /> - + {!!isEditForm && ( - deleteUserAddress(addressId!)} variant="xs" textAlign="center" mb={2} color="red"> + deleteUserAddress(addressId!)} + variant="xs" + textAlign="center" + mb={2} + color="red" + > Delete address )} diff --git a/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tests.tsx b/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tests.tsx index f1922218524..4ea9323e23b 100644 --- a/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tests.tsx +++ b/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tests.tsx @@ -103,7 +103,9 @@ describe("CreateSavedSearchAlert", () => { }) it("the push notification toggle is disabled by default when push permissions are not determined", async () => { - notificationPermissions.mockImplementation((cb) => cb(null, PushAuthorizationStatus.NotDetermined)) + notificationPermissions.mockImplementation((cb) => + cb(null, PushAuthorizationStatus.NotDetermined) + ) const { findAllByA11yState } = renderWithWrappersTL() const toggles = await findAllByA11yState({ selected: false }) diff --git a/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tsx b/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tsx index 778ce92c954..f1e57b65719 100644 --- a/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tsx +++ b/src/lib/Scenes/SavedSearchAlert/Components/CreateSavedSearchContent.tsx @@ -1,5 +1,8 @@ import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader" -import { getNotificationPermissionsStatus, PushAuthorizationStatus } from "lib/utils/PushNotification" +import { + getNotificationPermissionsStatus, + PushAuthorizationStatus, +} from "lib/utils/PushNotification" import useAppState from "lib/utils/useAppState" import { Box } from "palette" import React, { useCallback, useEffect, useState } from "react" diff --git a/src/lib/Scenes/SavedSearchAlert/Components/Form.tsx b/src/lib/Scenes/SavedSearchAlert/Components/Form.tsx index 3f3f46b56c2..02dd834a88d 100644 --- a/src/lib/Scenes/SavedSearchAlert/Components/Form.tsx +++ b/src/lib/Scenes/SavedSearchAlert/Components/Form.tsx @@ -2,7 +2,18 @@ import { useFormikContext } from "formik" import { SearchCriteria } from "lib/Components/ArtworkFilter/SavedSearch/types" import { navigate } from "lib/navigation/navigate" import { useFeatureFlag } from "lib/store/GlobalStore" -import { Box, Button, CloseIcon as RemoveIcon, Flex, Input, InputTitle, Pill, Spacer, Text, Touchable } from "palette" +import { + Box, + Button, + CloseIcon as RemoveIcon, + Flex, + Input, + InputTitle, + Pill, + Spacer, + Text, + Touchable, +} from "palette" import React from "react" import { LayoutAnimation } from "react-native" import { getNamePlaceholder } from "../helpers" @@ -156,9 +167,17 @@ export const Form: React.FC = (props) => { )} - + - + {!!values.email && ( = (props) => { {!!isEditMode && ( <> - diff --git a/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tests.tsx b/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tests.tsx index 4967cc2b807..f5716c01ddd 100644 --- a/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tests.tsx +++ b/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tests.tsx @@ -7,7 +7,9 @@ describe("SavedSearchAlertSwitch", () => { const onChangeMock = jest.fn() const TestRenderer = (props: Partial) => { - return + return ( + + ) } afterEach(() => { diff --git a/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tsx b/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tsx index 5b5f7e9b2eb..e1133261e88 100644 --- a/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tsx +++ b/src/lib/Scenes/SavedSearchAlert/Components/SavedSearchAlertSwitch.tsx @@ -9,7 +9,11 @@ export interface SavedSearchAlertSwitchProps { description?: string } -export const SavedSearchAlertSwitch = ({ onChange, active, label }: SavedSearchAlertSwitchProps) => { +export const SavedSearchAlertSwitch = ({ + onChange, + active, + label, +}: SavedSearchAlertSwitchProps) => { const color = useColor() let thumbColor = color("white100") let disabledTrackColor = color("black30") diff --git a/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tests.tsx b/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tests.tsx index 65b3a6bd0af..86d6c3cea13 100644 --- a/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tests.tsx +++ b/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tests.tsx @@ -1,6 +1,9 @@ import { CreateSavedSearchAlertTestsQuery } from "__generated__/CreateSavedSearchAlertTestsQuery.graphql" import { FilterData, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { ArtworkFiltersState, ArtworkFiltersStoreProvider } from "lib/Components/ArtworkFilter/ArtworkFilterStore" +import { + ArtworkFiltersState, + ArtworkFiltersStoreProvider, +} from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { defaultEnvironment } from "lib/relay/createEnvironment" import { __globalStoreTestUtils__ } from "lib/store/GlobalStore" import { mockEnvironmentPayload } from "lib/tests/mockEnvironmentPayload" @@ -86,7 +89,10 @@ describe("CreateSavedSearchAlert", () => { ) } - const renderAndExecuteQuery = (props?: Partial, mockResolvers?: MockResolvers) => { + const renderAndExecuteQuery = ( + props?: Partial, + mockResolvers?: MockResolvers + ) => { const render = renderWithWrappersTL() // CreateSavedSearchAlertTestsQuery diff --git a/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tsx b/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tsx index 14ccd1016eb..39039a64671 100644 --- a/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tsx +++ b/src/lib/Scenes/SavedSearchAlert/CreateSavedSearchAlert.tsx @@ -3,7 +3,10 @@ import { createStackNavigator, TransitionPresets } from "@react-navigation/stack import { FancyModal } from "lib/Components/FancyModal/FancyModal" import { Box } from "palette" import React from "react" -import { CreateSavedSearchAlertNavigationStack, CreateSavedSearchAlertProps } from "./SavedSearchAlertModel" +import { + CreateSavedSearchAlertNavigationStack, + CreateSavedSearchAlertProps, +} from "./SavedSearchAlertModel" import { CreateSavedSearchAlertScreen } from "./screens/CreateSavedSearchAlertScreen" import { EmailPreferencesScreen } from "./screens/EmailPreferencesScreen" diff --git a/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tests.tsx b/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tests.tsx index 337e76d9d45..7a97286630c 100644 --- a/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tests.tsx +++ b/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tests.tsx @@ -22,7 +22,9 @@ describe("EditSavedSearchAlert", () => { beforeEach(() => { mockEnvironment.mockClear() - notificationPermissions.mockImplementationOnce((cb) => cb(null, PushAuthorizationStatus.Authorized)) + notificationPermissions.mockImplementationOnce((cb) => + cb(null, PushAuthorizationStatus.Authorized) + ) }) const TestRenderer = () => { diff --git a/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tsx b/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tsx index 97bde510067..2e2b0c262dc 100644 --- a/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tsx +++ b/src/lib/Scenes/SavedSearchAlert/EditSavedSearchAlert.tsx @@ -91,7 +91,9 @@ export const EditSavedSearchAlertFragmentContainer = createFragmentContainer(Edi `, }) -export const EditSavedSearchAlertQueryRenderer: React.FC = (props) => { +export const EditSavedSearchAlertQueryRenderer: React.FC = ( + props +) => { const { savedSearchAlertId } = props return ( diff --git a/src/lib/Scenes/SavedSearchAlert/SavedSearchAlert.tsx b/src/lib/Scenes/SavedSearchAlert/SavedSearchAlert.tsx index b9c120a756b..c4e21ba4f5e 100644 --- a/src/lib/Scenes/SavedSearchAlert/SavedSearchAlert.tsx +++ b/src/lib/Scenes/SavedSearchAlert/SavedSearchAlert.tsx @@ -1,4 +1,7 @@ -import { SavedSearchAlertQuery, SavedSearchAlertQueryResponse } from "__generated__/SavedSearchAlertQuery.graphql" +import { + SavedSearchAlertQuery, + SavedSearchAlertQueryResponse, +} from "__generated__/SavedSearchAlertQuery.graphql" import { defaultEnvironment } from "lib/relay/createEnvironment" import React from "react" import { graphql, QueryRenderer } from "react-relay" diff --git a/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tests.tsx b/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tests.tsx index 8f2c52d9100..e19301a9eb7 100644 --- a/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tests.tsx +++ b/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tests.tsx @@ -26,7 +26,9 @@ describe("Saved search alert form", () => { beforeEach(() => { spyAlert.mockClear() mockEnvironment.mockClear() - notificationPermissions.mockImplementationOnce((cb) => cb(null, PushAuthorizationStatus.Authorized)) + notificationPermissions.mockImplementationOnce((cb) => + cb(null, PushAuthorizationStatus.Authorized) + ) }) const TestRenderer = (props: Partial) => { @@ -44,7 +46,9 @@ describe("Saved search alert form", () => { it("correctly renders placeholder for input name", () => { const { getByTestId } = renderWithWrappersTL() - expect(getByTestId("alert-input-name").props.placeholder).toEqual(`artistName ${bullet} 5 filters`) + expect(getByTestId("alert-input-name").props.placeholder).toEqual( + `artistName ${bullet} 5 filters` + ) }) it("correctly extracts the values of pills", () => { @@ -74,13 +78,17 @@ describe("Saved search alert form", () => { }) it(`should render "Delete Alert" button when the savedSearchAlertId is passed`, () => { - const { getAllByTestId } = renderWithWrappersTL() + const { getAllByTestId } = renderWithWrappersTL( + + ) expect(getAllByTestId("delete-alert-button")).toHaveLength(1) }) it("calls update mutation when form is submitted", async () => { - const { getByTestId } = renderWithWrappersTL() + const { getByTestId } = renderWithWrappersTL( + + ) fireEvent.changeText(getByTestId("alert-input-name"), "something new") fireEvent.press(getByTestId("save-alert-button")) @@ -103,7 +111,9 @@ describe("Saved search alert form", () => { }) it("tracks the edited saved search event when the save alert button is pressed", async () => { - const { getByTestId } = renderWithWrappersTL() + const { getByTestId } = renderWithWrappersTL( + + ) fireEvent.changeText(getByTestId("alert-input-name"), "something new") fireEvent.press(getByTestId("save-alert-button")) @@ -181,7 +191,9 @@ describe("Saved search alert form", () => { }) it("tracks clicks when the delete alert button is pressed", async () => { - const { getByTestId } = renderWithWrappersTL() + const { getByTestId } = renderWithWrappersTL( + + ) fireEvent.press(getByTestId("delete-alert-button")) fireEvent.press(getByTestId("dialog-primary-action-button")) @@ -328,7 +340,9 @@ describe("Saved search alert form", () => { it("the push notification toggle keeps in the same state when push permissions are not not determined", async () => { notificationPermissions.mockReset() - notificationPermissions.mockImplementation((cb) => cb(null, PushAuthorizationStatus.NotDetermined)) + notificationPermissions.mockImplementation((cb) => + cb(null, PushAuthorizationStatus.NotDetermined) + ) const { getByA11yLabel, queryAllByA11yState } = renderWithWrappersTL( @@ -545,7 +559,9 @@ describe("Saved search alert form", () => { it("should be enabled if name is changed and there is a saved alert with the same criteria", () => { __globalStoreTestUtils__?.injectFeatureFlags({ AREnableImprovedAlertsFlow: true }) - const { getByPlaceholderText, getAllByText } = renderWithWrappersTL() + const { getByPlaceholderText, getAllByText } = renderWithWrappersTL( + + ) expect(getAllByText("Save Alert")[0]).toBeDisabled() fireEvent.changeText(getByPlaceholderText(`artistName ${bullet} 5 filters`), "new value") @@ -554,7 +570,9 @@ describe("Saved search alert form", () => { it("should be enabled if notification toggles are changed and there is a saved alert with the same criteria", () => { __globalStoreTestUtils__?.injectFeatureFlags({ AREnableImprovedAlertsFlow: true }) - const { getByA11yLabel, getAllByText } = renderWithWrappersTL() + const { getByA11yLabel, getAllByText } = renderWithWrappersTL( + + ) expect(getAllByText("Save Alert")[0]).toBeDisabled() fireEvent(getByA11yLabel("Email Alerts Toggler"), "valueChange", false) @@ -563,7 +581,9 @@ describe("Saved search alert form", () => { it("should be enabled if filters are changed in edit mode", () => { __globalStoreTestUtils__?.injectFeatureFlags({ AREnableImprovedAlertsFlow: true }) - const { getByText, getAllByText } = renderWithWrappersTL() + const { getByText, getAllByText } = renderWithWrappersTL( + + ) expect(getAllByText("Save Alert")[0]).toBeDisabled() fireEvent.press(getByText("Limited Edition")) diff --git a/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tsx b/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tsx index 5e1738d0caa..4ae1f94f4d2 100644 --- a/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tsx +++ b/src/lib/Scenes/SavedSearchAlert/SavedSearchAlertForm.tsx @@ -7,7 +7,11 @@ import React, { useEffect, useState } from "react" import { Alert, ScrollView, StyleProp, ViewStyle } from "react-native" import { useTracking } from "react-tracking" import { Form } from "./Components/Form" -import { checkOrRequestPushPermissions, clearDefaultAttributes, getNamePlaceholder } from "./helpers" +import { + checkOrRequestPushPermissions, + clearDefaultAttributes, + getNamePlaceholder, +} from "./helpers" import { createSavedSearchAlert } from "./mutations/createSavedSearchAlert" import { deleteSavedSearchMutation } from "./mutations/deleteSavedSearchAlert" import { updateEmailFrequency } from "./mutations/updateEmailFrequency" @@ -94,7 +98,11 @@ export const SavedSearchAlertForm: React.FC = (props) if (isUpdateForm) { const criteria = isEnabledImprovedAlertsFlow ? clearedAttributes : undefined - const response = await updateSavedSearchAlert(savedSearchAlertId!, userAlertSettings, criteria) + const response = await updateSavedSearchAlert( + savedSearchAlertId!, + userAlertSettings, + criteria + ) tracking.trackEvent(tracks.editedSavedSearch(savedSearchAlertId!, initialValues, values)) result = { diff --git a/src/lib/Scenes/SavedSearchAlert/SavedSearchStore.tsx b/src/lib/Scenes/SavedSearchAlert/SavedSearchStore.tsx index ebe3be98ed1..5ad1bcb8ee9 100644 --- a/src/lib/Scenes/SavedSearchAlert/SavedSearchStore.tsx +++ b/src/lib/Scenes/SavedSearchAlert/SavedSearchStore.tsx @@ -1,6 +1,9 @@ import { action, Action, computed, Computed, createContextStore, State } from "easy-peasy" import { Aggregations } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { SearchCriteria, SearchCriteriaAttributes } from "lib/Components/ArtworkFilter/SavedSearch/types" +import { + SearchCriteria, + SearchCriteriaAttributes, +} from "lib/Components/ArtworkFilter/SavedSearch/types" import { extractPills } from "./pillExtractors" import { SavedSearchPill } from "./SavedSearchAlertModel" @@ -31,7 +34,9 @@ const savedSearchModel: SavedSearchModel = { const prevValue = state.attributes[payload.key] if (Array.isArray(prevValue)) { - ;(state.attributes[payload.key] as string[]) = prevValue.filter((value) => value !== payload.value) + ;(state.attributes[payload.key] as string[]) = prevValue.filter( + (value) => value !== payload.value + ) } else { state.attributes[payload.key] = null } diff --git a/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV1.tsx b/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV1.tsx index d3e2e325811..8d03a9560a6 100644 --- a/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV1.tsx +++ b/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV1.tsx @@ -4,7 +4,10 @@ import { CreateSavedSearchContentContainerV1_me } from "__generated__/CreateSave import React, { useCallback, useState } from "react" import { createRefetchContainer, graphql, RelayRefetchProp } from "react-relay" import { CreateSavedSearchContent } from "../Components/CreateSavedSearchContent" -import { CreateSavedSearchAlertNavigationStack, CreateSavedSearchAlertParams } from "../SavedSearchAlertModel" +import { + CreateSavedSearchAlertNavigationStack, + CreateSavedSearchAlertParams, +} from "../SavedSearchAlertModel" interface ContainerProps extends Omit { navigation: StackNavigationProp diff --git a/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV2.tsx b/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV2.tsx index 58c618313ca..2be40511a05 100644 --- a/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV2.tsx +++ b/src/lib/Scenes/SavedSearchAlert/containers/CreateSavedSearchContentContainerV2.tsx @@ -103,9 +103,9 @@ const CreateSavedSearchContentContainerV2 = createRefetchContainer( ` ) -export const CreateSavedSearchAlertContentQueryRenderer: React.FC = ( - props -) => { +export const CreateSavedSearchAlertContentQueryRenderer: React.FC< + CreateSavedSearchAlertContentQueryRendererProps +> = (props) => { const { artistId } = props const filterState = ArtworksFiltersStore.useStoreState((state) => state) const unitedFilters = getUnitedSelectedAndAppliedFilters(filterState) diff --git a/src/lib/Scenes/SavedSearchAlert/helpers.tests.ts b/src/lib/Scenes/SavedSearchAlert/helpers.tests.ts index cfb71ba6f9b..c283886e57a 100644 --- a/src/lib/Scenes/SavedSearchAlert/helpers.tests.ts +++ b/src/lib/Scenes/SavedSearchAlert/helpers.tests.ts @@ -1,11 +1,16 @@ -import { SearchCriteria, SearchCriteriaAttributes } from "lib/Components/ArtworkFilter/SavedSearch/types" +import { + SearchCriteria, + SearchCriteriaAttributes, +} from "lib/Components/ArtworkFilter/SavedSearch/types" import { __globalStoreTestUtils__ } from "lib/store/GlobalStore" import { clearDefaultAttributes, getNamePlaceholder } from "./helpers" import { SavedSearchPill } from "./SavedSearchAlertModel" describe("getNamePlaceholder", () => { it("returns the singular form for the filter label", () => { - const pills: SavedSearchPill[] = [{ label: "One", paramName: SearchCriteria.materialsTerms, value: "one" }] + const pills: SavedSearchPill[] = [ + { label: "One", paramName: SearchCriteria.materialsTerms, value: "one" }, + ] expect(getNamePlaceholder("artistName", pills)).toBe("artistName • 1 filter") }) diff --git a/src/lib/Scenes/SavedSearchAlert/helpers.ts b/src/lib/Scenes/SavedSearchAlert/helpers.ts index 694823650f5..6e6aa3025b8 100644 --- a/src/lib/Scenes/SavedSearchAlert/helpers.ts +++ b/src/lib/Scenes/SavedSearchAlert/helpers.ts @@ -1,6 +1,12 @@ -import { SearchCriteria, SearchCriteriaAttributes } from "lib/Components/ArtworkFilter/SavedSearch/types" +import { + SearchCriteria, + SearchCriteriaAttributes, +} from "lib/Components/ArtworkFilter/SavedSearch/types" import { LegacyNativeModules } from "lib/NativeModules/LegacyNativeModules" -import { getNotificationPermissionsStatus, PushAuthorizationStatus } from "lib/utils/PushNotification" +import { + getNotificationPermissionsStatus, + PushAuthorizationStatus, +} from "lib/utils/PushNotification" import { bullet } from "palette" import { Alert, AlertButton, Linking, Platform } from "react-native" import { SavedSearchPill } from "./SavedSearchAlertModel" @@ -25,7 +31,8 @@ export const requestNotificationPermissions = () => { [ { text: "Proceed", - onPress: () => LegacyNativeModules.ARTemporaryAPIModule.requestDirectNotificationPermissions(), + onPress: () => + LegacyNativeModules.ARTemporaryAPIModule.requestDirectNotificationPermissions(), }, { text: "Cancel", diff --git a/src/lib/Scenes/SavedSearchAlert/mutations/updateEmailFrequency.ts b/src/lib/Scenes/SavedSearchAlert/mutations/updateEmailFrequency.ts index 5145cfd9323..6abfc340d35 100644 --- a/src/lib/Scenes/SavedSearchAlert/mutations/updateEmailFrequency.ts +++ b/src/lib/Scenes/SavedSearchAlert/mutations/updateEmailFrequency.ts @@ -5,7 +5,9 @@ import { import { defaultEnvironment } from "lib/relay/createEnvironment" import { commitMutation, graphql } from "relay-runtime" -export const updateEmailFrequency = (emailFrequency: string): Promise => { +export const updateEmailFrequency = ( + emailFrequency: string +): Promise => { return new Promise((resolve, reject) => { commitMutation(defaultEnvironment, { mutation: graphql` diff --git a/src/lib/Scenes/SavedSearchAlert/pillExtractors.tests.ts b/src/lib/Scenes/SavedSearchAlert/pillExtractors.tests.ts index ab584d3557d..1027c70b223 100644 --- a/src/lib/Scenes/SavedSearchAlert/pillExtractors.tests.ts +++ b/src/lib/Scenes/SavedSearchAlert/pillExtractors.tests.ts @@ -1,10 +1,17 @@ import { Aggregations } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" -import { SearchCriteria, SearchCriteriaAttributes } from "lib/Components/ArtworkFilter/SavedSearch/types" +import { + SearchCriteria, + SearchCriteriaAttributes, +} from "lib/Components/ArtworkFilter/SavedSearch/types" import { extractPillFromAggregation, extractPills, extractSizeLabel } from "./pillExtractors" describe("extractPillFromAggregation", () => { it("returns pills", () => { - const result = extractPillFromAggregation(SearchCriteria.materialsTerms, ["acrylic", "canvas"], aggregations) + const result = extractPillFromAggregation( + SearchCriteria.materialsTerms, + ["acrylic", "canvas"], + aggregations + ) const pills = [ { label: "Acrylic", value: "acrylic", paramName: SearchCriteria.materialsTerms }, @@ -31,7 +38,11 @@ describe("extractPillFromAggregation", () => { }) it("returns empty array when couldn't get aggregation by param name", () => { - const result = extractPillFromAggregation(SearchCriteria.materialsTerms, ["acrylic", "canvas", "unknown-value"], []) + const result = extractPillFromAggregation( + SearchCriteria.materialsTerms, + ["acrylic", "canvas", "unknown-value"], + [] + ) expect(result).toEqual([]) }) diff --git a/src/lib/Scenes/SavedSearchAlert/pillExtractors.ts b/src/lib/Scenes/SavedSearchAlert/pillExtractors.ts index fe39a87dc76..1ebea551de4 100644 --- a/src/lib/Scenes/SavedSearchAlert/pillExtractors.ts +++ b/src/lib/Scenes/SavedSearchAlert/pillExtractors.ts @@ -13,13 +13,23 @@ import { parseRange, } from "lib/Components/ArtworkFilter/Filters/helpers" import { SIZES_OPTIONS } from "lib/Components/ArtworkFilter/Filters/SizesOptionsScreen" -import { WAYS_TO_BUY_OPTIONS, WAYS_TO_BUY_PARAM_NAMES } from "lib/Components/ArtworkFilter/Filters/WaysToBuyOptions" +import { + WAYS_TO_BUY_OPTIONS, + WAYS_TO_BUY_PARAM_NAMES, +} from "lib/Components/ArtworkFilter/Filters/WaysToBuyOptions" import { shouldExtractValueNamesFromAggregation } from "lib/Components/ArtworkFilter/SavedSearch/constants" -import { SearchCriteria, SearchCriteriaAttributes } from "lib/Components/ArtworkFilter/SavedSearch/types" +import { + SearchCriteria, + SearchCriteriaAttributes, +} from "lib/Components/ArtworkFilter/SavedSearch/types" import { compact, flatten, isNil, isUndefined, keyBy } from "lodash" import { SavedSearchPill } from "./SavedSearchAlertModel" -export const extractPillFromAggregation = (paramName: SearchCriteria, values: string[], aggregations: Aggregations) => { +export const extractPillFromAggregation = ( + paramName: SearchCriteria, + values: string[], + aggregations: Aggregations +) => { const aggregation = aggregationForFilter(paramName, aggregations) if (aggregation) { @@ -124,7 +134,10 @@ export const extractWaysToBuyPill = (paramName: SearchCriteria): SavedSearchPill } } -export const extractPills = (attributes: SearchCriteriaAttributes, aggregations: Aggregations): SavedSearchPill[] => { +export const extractPills = ( + attributes: SearchCriteriaAttributes, + aggregations: Aggregations +): SavedSearchPill[] => { const pills = Object.entries(attributes).map((entry) => { const [paramName, paramValue] = entry as [SearchCriteria, any] diff --git a/src/lib/Scenes/SavedSearchAlert/screens/CreateSavedSearchAlertScreen.tsx b/src/lib/Scenes/SavedSearchAlert/screens/CreateSavedSearchAlertScreen.tsx index 029b1ce35a0..b3772f974fe 100644 --- a/src/lib/Scenes/SavedSearchAlert/screens/CreateSavedSearchAlertScreen.tsx +++ b/src/lib/Scenes/SavedSearchAlert/screens/CreateSavedSearchAlertScreen.tsx @@ -23,7 +23,9 @@ export const CreateSavedSearchAlertScreen: React.FC = (props) => { const attributes = getSearchCriteriaFromFilters(route.params.artistId, unitedFilters) return ( - + { - Filter for the artworks you love on an Artist Page and tap ‘Create Alert’ to be notified when new works are - added to Artsy. + Filter for the artworks you love on an Artist Page and tap ‘Create Alert’ to be notified + when new works are added to Artsy. diff --git a/src/lib/Scenes/SavedSearchAlertsList/SavedSearchAlertsList.tsx b/src/lib/Scenes/SavedSearchAlertsList/SavedSearchAlertsList.tsx index 1bff7b70d7d..fe86b79b17b 100644 --- a/src/lib/Scenes/SavedSearchAlertsList/SavedSearchAlertsList.tsx +++ b/src/lib/Scenes/SavedSearchAlertsList/SavedSearchAlertsList.tsx @@ -22,13 +22,16 @@ export const SavedSearchAlertsList: React.FC = (prop ) } -export const SavedSearchAlertsListFragmentContainer = createFragmentContainer(SavedSearchAlertsList, { - me: graphql` - fragment SavedSearchAlertsList_me on Me { - ...SavedSearchesList_me - } - `, -}) +export const SavedSearchAlertsListFragmentContainer = createFragmentContainer( + SavedSearchAlertsList, + { + me: graphql` + fragment SavedSearchAlertsList_me on Me { + ...SavedSearchesList_me + } + `, + } +) export const SavedSearchAlertsListQueryRenderer: React.FC = () => { return ( diff --git a/src/lib/Scenes/Search/AutosuggestResults.tests.tsx b/src/lib/Scenes/Search/AutosuggestResults.tests.tsx index 1a0a7b960b3..a0e28fed26c 100644 --- a/src/lib/Scenes/Search/AutosuggestResults.tests.tsx +++ b/src/lib/Scenes/Search/AutosuggestResults.tests.tsx @@ -101,7 +101,9 @@ const FixtureEmpty: AutosuggestResultsQueryRawResponse = { const inputBlurMock = jest.fn() const TestWrapper: typeof AutosuggestResults = (props) => ( - + @@ -132,7 +134,10 @@ const notifyRecentSearchMock = require("./RecentSearches").useRecentSearches().n const env = defaultEnvironment as any as ReturnType const consoleErrorMock = jest.fn() -const whiteListErrors = ["Warning: An update to %s inside a test was not wrapped in act(...).", "Bad connection"] +const whiteListErrors = [ + "Warning: An update to %s inside a test was not wrapped in act(...).", + "Bad connection", +] console.error = (...args: any[]) => { let error = args[0] @@ -168,7 +173,9 @@ describe("AutosuggestResults", () => { const tree = renderWithWrappers() expect(tree.root.findAllByType(AutosuggestSearchResult)).toHaveLength(0) - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("AutosuggestResultsQuery") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "AutosuggestResultsQuery" + ) expect(env.mock.getMostRecentOperation().request.variables.query).toBe("michael") act(() => { @@ -197,7 +204,9 @@ describe("AutosuggestResults", () => { tree.root.findByType(AboveTheFoldFlatList).props.onScrollBeginDrag() }) expect(env.mock.getAllOperations()).toHaveLength(1) - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("AutosuggestResultsPaginationQuery") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "AutosuggestResultsPaginationQuery" + ) expect(env.mock.getMostRecentOperation().request.variables.cursor).toBe("page-2") act(() => { @@ -213,7 +222,9 @@ describe("AutosuggestResults", () => { tree.root.findByType(AboveTheFoldFlatList).props.onEndReached() }) expect(env.mock.getAllOperations()).toHaveLength(1) - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("AutosuggestResultsPaginationQuery") + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "AutosuggestResultsPaginationQuery" + ) expect(env.mock.getMostRecentOperation().request.variables.cursor).toBe("page-3") act(() => { @@ -232,7 +243,8 @@ describe("AutosuggestResults", () => { env.mock.resolveMostRecentOperation({ errors: [], data: FixturePage1 }) }) const scrollToOffsetMock = jest.fn() - tree.root.findByType(AboveTheFoldFlatList).findByType(FlatList).instance.scrollToOffset = scrollToOffsetMock + tree.root.findByType(AboveTheFoldFlatList).findByType(FlatList).instance.scrollToOffset = + scrollToOffsetMock act(() => { tree.update() @@ -266,7 +278,9 @@ describe("AutosuggestResults", () => { expect(tree.root.findAllByType(AutosuggestSearchResult)).toHaveLength(0) expect(extractText(tree.root)).toContain("Sorry, we couldn’t find anything for “michael.”") - expect(extractText(tree.root)).toContain("Please try searching again with a different spelling.") + expect(extractText(tree.root)).toContain( + "Please try searching again with a different spelling." + ) }) it(`optionally hides the result type`, () => { @@ -277,7 +291,9 @@ describe("AutosuggestResults", () => { it(`allows for custom touch handlers on search result items`, () => { const spy = jest.fn() - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) act(() => env.mock.resolveMostRecentOperation({ errors: [], data: FixturePage1 })) tree.root.findByType(AutosuggestSearchResult).props.onResultPress() expect(spy).toHaveBeenCalled() @@ -302,11 +318,15 @@ describe("AutosuggestResults", () => { act(() => env.mock.rejectMostRecentOperation(new Error("Bad connection"))) - expect(getByText("There seems to be a problem with the connection. Please try again shortly.")).toBeTruthy() + expect( + getByText("There seems to be a problem with the connection. Please try again shortly.") + ).toBeTruthy() }) it("should show the unable to load error message when showOnRetryErrorMessage prop is true", () => { - const { getByText } = renderWithWrappersTL() + const { getByText } = renderWithWrappersTL( + + ) act(() => env.mock.rejectMostRecentOperation(new Error("Bad connection"))) diff --git a/src/lib/Scenes/Search/AutosuggestResults.tsx b/src/lib/Scenes/Search/AutosuggestResults.tsx index 5562210ad1e..8f468e08a37 100644 --- a/src/lib/Scenes/Search/AutosuggestResults.tsx +++ b/src/lib/Scenes/Search/AutosuggestResults.tsx @@ -16,7 +16,11 @@ import React from "react" import { FlatList } from "react-native" import { createPaginationContainer, graphql, QueryRenderer, RelayPaginationProp } from "react-relay" import usePrevious from "react-use/lib/usePrevious" -import { AutosuggestSearchResult, OnResultPress, TrackResultPress } from "./components/AutosuggestSearchResult" +import { + AutosuggestSearchResult, + OnResultPress, + TrackResultPress, +} from "./components/AutosuggestSearchResult" import { AutosuggestResultsPlaceholder } from "./components/placeholders/AutosuggestResultsPlaceholder" export type AutosuggestResult = NonNullable< @@ -105,12 +109,15 @@ const AutosuggestResultsFlatList: React.FC<{ results.current = latestResults || results.current const nodes: AutosuggestResult[] = useMemo( - () => results.current?.results?.edges?.map((e, i) => ({ ...e?.node!, key: e?.node?.href! + i })) ?? [], + () => + results.current?.results?.edges?.map((e, i) => ({ ...e?.node!, key: e?.node?.href! + i })) ?? + [], [results.current] ) // We want to show a loading spinner at the bottom so long as there are more results to be had - const hasMoreResults = results.current && results.current.results?.edges?.length! > 0 && relay.hasMore() + const hasMoreResults = + results.current && results.current.results?.edges?.length! > 0 && relay.hasMore() const ListFooterComponent = useMemo(() => { return () => ( @@ -188,10 +195,18 @@ const AutosuggestResultsContainer = createPaginationContainer( query: { type: "String!" } count: { type: "Int!" } cursor: { type: "String" } - entities: { type: "[SearchEntity]", defaultValue: [ARTIST, ARTWORK, FAIR, GENE, SALE, PROFILE, COLLECTION] } + entities: { + type: "[SearchEntity]" + defaultValue: [ARTIST, ARTWORK, FAIR, GENE, SALE, PROFILE, COLLECTION] + } ) { - results: searchConnection(query: $query, mode: AUTOSUGGEST, first: $count, after: $cursor, entities: $entities) - @connection(key: "AutosuggestResults_results") { + results: searchConnection( + query: $query + mode: AUTOSUGGEST + first: $count + after: $cursor + entities: $entities + ) @connection(key: "AutosuggestResults_results") { edges { node { imageUrl @@ -230,9 +245,14 @@ const AutosuggestResultsContainer = createPaginationContainer( } }, query: graphql` - query AutosuggestResultsPaginationQuery($query: String!, $count: Int!, $cursor: String, $entities: [SearchEntity]) - @raw_response_type { - ...AutosuggestResults_results @arguments(query: $query, count: $count, cursor: $cursor, entities: $entities) + query AutosuggestResultsPaginationQuery( + $query: String! + $count: Int! + $cursor: String + $entities: [SearchEntity] + ) @raw_response_type { + ...AutosuggestResults_results + @arguments(query: $query, count: $count, cursor: $cursor, entities: $entities) } `, } @@ -297,8 +317,10 @@ export const AutosuggestResults: React.FC<{ entities, }} query={graphql` - query AutosuggestResultsQuery($query: String!, $count: Int!, $entities: [SearchEntity]) @raw_response_type { - ...AutosuggestResults_results @arguments(query: $query, count: $count, entities: $entities) + query AutosuggestResultsQuery($query: String!, $count: Int!, $entities: [SearchEntity]) + @raw_response_type { + ...AutosuggestResults_results + @arguments(query: $query, count: $count, entities: $entities) } `} environment={defaultEnvironment} diff --git a/src/lib/Scenes/Search/RecentSearches.tests.tsx b/src/lib/Scenes/Search/RecentSearches.tests.tsx index a16a7cfc767..ab006d08961 100644 --- a/src/lib/Scenes/Search/RecentSearches.tests.tsx +++ b/src/lib/Scenes/Search/RecentSearches.tests.tsx @@ -85,7 +85,9 @@ describe("Recent Searches", () => { it("has an empty state", () => { const tree = renderWithWrappers() - expect(extractText(tree.root)).toMatchInlineSnapshot(`"Recent SearchesWe’ll save your recent searches here"`) + expect(extractText(tree.root)).toMatchInlineSnapshot( + `"Recent SearchesWe’ll save your recent searches here"` + ) expect(tree.root.findAllByType(AutosuggestSearchResult)).toHaveLength(0) }) diff --git a/src/lib/Scenes/Search/RecentSearches.tsx b/src/lib/Scenes/Search/RecentSearches.tsx index 6561f5e360b..6c51530b3e5 100644 --- a/src/lib/Scenes/Search/RecentSearches.tsx +++ b/src/lib/Scenes/Search/RecentSearches.tsx @@ -22,7 +22,10 @@ export const RecentSearches: React.FC = () => { updateRecentSearchesOnTap={false} displayingRecentResult onDelete={() => { - LayoutAnimation.configureNext({ ...LayoutAnimation.Presets.easeInEaseOut, duration: 230 }) + LayoutAnimation.configureNext({ + ...LayoutAnimation.Presets.easeInEaseOut, + duration: 230, + }) GlobalStore.actions.search.deleteRecentSearch(result) }} /> diff --git a/src/lib/Scenes/Search/Search.tests.tsx b/src/lib/Scenes/Search/Search.tests.tsx index 044583dd006..ce1448d353f 100644 --- a/src/lib/Scenes/Search/Search.tests.tsx +++ b/src/lib/Scenes/Search/Search.tests.tsx @@ -118,7 +118,9 @@ describe("Search Screen", () => { }) it("should not be able to untoggle the same pill", () => { - const { getByPlaceholderText, getByText, getByA11yState } = renderWithWrappersTL() + const { getByPlaceholderText, getByText, getByA11yState } = renderWithWrappersTL( + + ) const searchInput = getByPlaceholderText("Search artists, artworks, galleries, etc") mockEnvironmentPayload(mockEnvironment, { @@ -414,7 +416,9 @@ describe("Search Screen", () => { }) it("should render only allowed algolia indices", () => { - const { getByPlaceholderText, getByText, queryByText } = renderWithWrappersTL() + const { getByPlaceholderText, getByText, queryByText } = renderWithWrappersTL( + + ) const searchInput = getByPlaceholderText("Search artists, artworks, galleries, etc") mockEnvironmentPayload(mockEnvironment, { diff --git a/src/lib/Scenes/Search/Search.tsx b/src/lib/Scenes/Search/Search.tsx index 8b7aa344162..434783eb511 100644 --- a/src/lib/Scenes/Search/Search.tsx +++ b/src/lib/Scenes/Search/Search.tsx @@ -86,16 +86,23 @@ export const Search: React.FC = (props) => { const [selectedPill, setSelectedPill] = useState(TOP_PILL) const searchProviderValues = useSearchProviderValues(searchState?.query ?? "") const { searchClient } = useAlgoliaClient(system?.algolia?.appID!, system?.algolia?.apiKey!) - const searchInsightsConfigured = useSearchInsightsConfig(system?.algolia?.appID, system?.algolia?.apiKey) + const searchInsightsConfigured = useSearchInsightsConfig( + system?.algolia?.appID, + system?.algolia?.apiKey + ) const indices = system?.algolia?.indices - const { loading: indicesInfoLoading, indicesInfo, updateIndicesInfo } = useAlgoliaIndices(searchClient, indices) + const { + loading: indicesInfoLoading, + indicesInfo, + updateIndicesInfo, + } = useAlgoliaIndices(searchClient, indices) const { trackEvent } = useTracking() const enableImprovedPills = useFeatureFlag("AREnableImprovedSearchPills") const pillsArray = useMemo(() => { if (Array.isArray(indices) && indices.length > 0) { - const allowedIndices = (indices as NonNullable["indices"]).filter((indice) => - ALLOWED_ALGOLIA_KEYS.includes(indice.key as AlgoliaIndexKey) + const allowedIndices = (indices as NonNullable["indices"]).filter( + (indice) => ALLOWED_ALGOLIA_KEYS.includes(indice.key as AlgoliaIndexKey) ) const formattedIndices: PillType[] = allowedIndices.map((index) => { const { name, ...other } = index diff --git a/src/lib/Scenes/Search/SearchArtworksContainer.tsx b/src/lib/Scenes/Search/SearchArtworksContainer.tsx index 29635df74f4..4a8b57ddfad 100644 --- a/src/lib/Scenes/Search/SearchArtworksContainer.tsx +++ b/src/lib/Scenes/Search/SearchArtworksContainer.tsx @@ -16,7 +16,8 @@ export const SearchArtworksQueryRenderer: React.FC<{ keyword: string }> = ({ key query={graphql` query SearchArtworksContainerQuery($count: Int!, $cursor: String, $keyword: String) { viewer { - ...SearchArtworksGrid_viewer @arguments(count: $count, cursor: $cursor, keyword: $keyword) + ...SearchArtworksGrid_viewer + @arguments(count: $count, cursor: $cursor, keyword: $keyword) } } `} diff --git a/src/lib/Scenes/Search/SearchArtworksGrid.tests.tsx b/src/lib/Scenes/Search/SearchArtworksGrid.tests.tsx index a7dbef85bc8..53817d5f37f 100644 --- a/src/lib/Scenes/Search/SearchArtworksGrid.tests.tsx +++ b/src/lib/Scenes/Search/SearchArtworksGrid.tests.tsx @@ -25,10 +25,14 @@ describe("SearchArtworksGrid", () => { environment={environment} query={graphql` - query SearchArtworksGridTestsQuery($input: FilterArtworksInput, $count: Int, $keyword: String) - @relay_test_operation { + query SearchArtworksGridTestsQuery( + $input: FilterArtworksInput + $count: Int + $keyword: String + ) @relay_test_operation { viewer { - ...SearchArtworksGrid_viewer @arguments(input: $input, keyword: $keyword, count: $count) + ...SearchArtworksGrid_viewer + @arguments(input: $input, keyword: $keyword, count: $count) } } `} diff --git a/src/lib/Scenes/Search/SearchArtworksGrid.tsx b/src/lib/Scenes/Search/SearchArtworksGrid.tsx index 2d1fcc7ba46..360a1bbf2a0 100644 --- a/src/lib/Scenes/Search/SearchArtworksGrid.tsx +++ b/src/lib/Scenes/Search/SearchArtworksGrid.tsx @@ -1,6 +1,9 @@ import { SearchArtworksGrid_viewer } from "__generated__/SearchArtworksGrid_viewer.graphql" import { ArtworkFilterNavigator, FilterModalMode } from "lib/Components/ArtworkFilter" -import { useArtworkFilters, useSelectedFiltersCount } from "lib/Components/ArtworkFilter/useArtworkFilters" +import { + useArtworkFilters, + useSelectedFiltersCount, +} from "lib/Components/ArtworkFilter/useArtworkFilters" import { InfiniteScrollArtworksGridContainer } from "lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid" import { OwnerType } from "@artsy/cohesion" @@ -29,7 +32,9 @@ const SearchArtworksGrid: React.FC = ({ viewer, relay, const { space } = useTheme() const { trackEvent } = useTracking() const [isFilterArtworksModalVisible, setFilterArtworkModalVisible] = useState(false) - const setFiltersCountAction = ArtworksFiltersStore.useStoreActions((state) => state.setFiltersCountAction) + const setFiltersCountAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setFiltersCountAction + ) const handleCloseFilterArtworksModal = (withFiltersApplying: boolean = false) => { if (!withFiltersApplying) { @@ -53,7 +58,10 @@ const SearchArtworksGrid: React.FC = ({ viewer, relay, useEffect(() => { if (viewer.artworks?.counts) { - setFiltersCountAction({ followedArtists: viewer.artworks.counts.followedArtists, total: null }) + setFiltersCountAction({ + followedArtists: viewer.artworks.counts.followedArtists, + total: null, + }) } }, [setFiltersCountAction]) @@ -83,7 +91,10 @@ const SearchArtworksGrid: React.FC = ({ viewer, relay, closeModal={handleCloseFilterArtworksModal} mode={FilterModalMode.Search} /> - + {artworksCount === 0 ? ( @@ -171,9 +182,15 @@ export const SearchArtworksGridPaginationContainer = createPaginationContainer( } }, query: graphql` - query SearchArtworksGridQuery($count: Int!, $cursor: String, $keyword: String, $input: FilterArtworksInput) { + query SearchArtworksGridQuery( + $count: Int! + $cursor: String + $keyword: String + $input: FilterArtworksInput + ) { viewer { - ...SearchArtworksGrid_viewer @arguments(count: $count, cursor: $cursor, keyword: $keyword, input: $input) + ...SearchArtworksGrid_viewer + @arguments(count: $count, cursor: $cursor, keyword: $keyword, input: $input) } } `, diff --git a/src/lib/Scenes/Search/SearchModel.tests.tsx b/src/lib/Scenes/Search/SearchModel.tests.tsx index 869a1f982fc..c7bb67fe2e6 100644 --- a/src/lib/Scenes/Search/SearchModel.tests.tsx +++ b/src/lib/Scenes/Search/SearchModel.tests.tsx @@ -2,7 +2,12 @@ import { __globalStoreTestUtils__, GlobalStore, GlobalStoreProvider } from "lib/ import { renderWithWrappers } from "lib/tests/renderWithWrappers" import { times } from "lodash" import React from "react" -import { MAX_SAVED_RECENT_SEARCHES, RecentSearch, SearchModel, useRecentSearches } from "./SearchModel" +import { + MAX_SAVED_RECENT_SEARCHES, + RecentSearch, + SearchModel, + useRecentSearches, +} from "./SearchModel" const banksy: RecentSearch = { type: "AUTOSUGGEST_RESULT_TAPPED", diff --git a/src/lib/Scenes/Search/SearchResults.tsx b/src/lib/Scenes/Search/SearchResults.tsx index e52a04ad12f..72dcee2114f 100644 --- a/src/lib/Scenes/Search/SearchResults.tsx +++ b/src/lib/Scenes/Search/SearchResults.tsx @@ -78,7 +78,9 @@ export const SearchResults: React.FC = ({ } if (searchResults?.nbHits === 0) { - const article = ALGOLIA_INDICES_WITH_AN_ARTICLE.includes(selectedPill.key as AlgoliaIndexKey) ? "an" : "a" + const article = ALGOLIA_INDICES_WITH_AN_ARTICLE.includes(selectedPill.key as AlgoliaIndexKey) + ? "an" + : "a" return ( @@ -102,7 +104,11 @@ export const SearchResults: React.FC = ({ keyExtractor={(item) => item.objectID} ItemSeparatorComponent={() => } renderItem={({ item }) => ( - + )} onEndReached={loadMore} ListFooterComponent={ diff --git a/src/lib/Scenes/Search/components/AutosuggestSearchResult.tests.tsx b/src/lib/Scenes/Search/components/AutosuggestSearchResult.tests.tsx index 6bff6b848c6..b8a3e4fe04b 100644 --- a/src/lib/Scenes/Search/components/AutosuggestSearchResult.tests.tsx +++ b/src/lib/Scenes/Search/components/AutosuggestSearchResult.tests.tsx @@ -80,7 +80,9 @@ describe(AutosuggestSearchResult, () => { }) it("calls onDelete calback when pressing on delete button", async () => { - const { getByA11yLabel } = renderWithWrappersTL() + const { getByA11yLabel } = renderWithWrappersTL( + + ) fireEvent.press(getByA11yLabel("Remove recent search item")) expect(onDeleteMock).toHaveBeenCalled() @@ -121,7 +123,9 @@ describe(AutosuggestSearchResult, () => { }) it(`won't update recent searches if told not to`, async () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(navigate).not.toHaveBeenCalled() expect(recentSearchesArray).toHaveLength(0) act(() => { @@ -160,7 +164,11 @@ describe(AutosuggestSearchResult, () => { tree.root.findByType(Touchable).props.onPress() }) await new Promise((r) => setTimeout(r, 50)) - expect(navigateToEntity).toHaveBeenCalledWith("/art-expo-diff-profile-slug", EntityType.Fair, SlugType.ProfileID) + expect(navigateToEntity).toHaveBeenCalledWith( + "/art-expo-diff-profile-slug", + EntityType.Fair, + SlugType.ProfileID + ) }) it(`shows navigation buttons when enabled and available`, async () => { @@ -247,13 +255,17 @@ describe(AutosuggestSearchResult, () => { tree.root.findAllByType(Pressable)[0].props.onPress() }) await new Promise((r) => setTimeout(r, 50)) - expect(navigate).toHaveBeenCalledWith("/artist/anto-carte", { passProps: { initialTab: "Artworks" } }) + expect(navigate).toHaveBeenCalledWith("/artist/anto-carte", { + passProps: { initialTab: "Artworks" }, + }) act(() => { tree.root.findAllByType(Pressable)[1].props.onPress() }) await new Promise((r) => setTimeout(r, 50)) - expect(navigate).toHaveBeenCalledWith("/artist/anto-carte", { passProps: { initialTab: "Insights" } }) + expect(navigate).toHaveBeenCalledWith("/artist/anto-carte", { + passProps: { initialTab: "Insights" }, + }) }) it("should call custom event track handler when search result is pressed", () => { diff --git a/src/lib/Scenes/Search/components/AutosuggestSearchResult.tsx b/src/lib/Scenes/Search/components/AutosuggestSearchResult.tsx index f877091daad..3cf5fec260e 100644 --- a/src/lib/Scenes/Search/components/AutosuggestSearchResult.tsx +++ b/src/lib/Scenes/Search/components/AutosuggestSearchResult.tsx @@ -1,4 +1,10 @@ -import { EntityType, navigate, navigateToEntity, navigateToPartner, SlugType } from "lib/navigation/navigate" +import { + EntityType, + navigate, + navigateToEntity, + navigateToPartner, + SlugType, +} from "lib/navigation/navigate" import { GlobalStore } from "lib/store/GlobalStore" import { Schema } from "lib/utils/track" import { ArtworkIcon, AuctionIcon, CloseIcon, Flex, Pill, Spacer, Text, Touchable } from "palette" @@ -64,7 +70,10 @@ export const AutosuggestSearchResult: React.FC<{ setTimeout(() => { navigateToResult(result, passProps?.artistTab) if (updateRecentSearchesOnTap) { - GlobalStore.actions.search.addRecentSearch({ type: "AUTOSUGGEST_RESULT_TAPPED", props: result }) + GlobalStore.actions.search.addRecentSearch({ + type: "AUTOSUGGEST_RESULT_TAPPED", + props: result, + }) } }, 20) @@ -89,7 +98,10 @@ export const AutosuggestSearchResult: React.FC<{ return ( <> - onPress()} testID={`autosuggest-search-result-${result.displayLabel}`}> + onPress()} + testID={`autosuggest-search-result-${result.displayLabel}`} + > @@ -131,11 +143,21 @@ export const AutosuggestSearchResult: React.FC<{ - onPress({ artistTab: "Artworks" })}> + onPress({ artistTab: "Artworks" })} + > Artworks - onPress({ artistTab: "Insights" })}> + onPress({ artistTab: "Insights" })} + > Auction Results diff --git a/src/lib/Scenes/Search/components/CityGuideCTA.tsx b/src/lib/Scenes/Search/components/CityGuideCTA.tsx index 8d0647a1390..6845a8b9cb5 100644 --- a/src/lib/Scenes/Search/components/CityGuideCTA.tsx +++ b/src/lib/Scenes/Search/components/CityGuideCTA.tsx @@ -14,7 +14,14 @@ export class CityGuideCTA extends React.Component { navigate("/local-discovery")}> - + diff --git a/src/lib/Scenes/Search/components/ImageSearchModal.tsx b/src/lib/Scenes/Search/components/ImageSearchModal.tsx index 4b95204d94a..cec318643df 100644 --- a/src/lib/Scenes/Search/components/ImageSearchModal.tsx +++ b/src/lib/Scenes/Search/components/ImageSearchModal.tsx @@ -16,7 +16,12 @@ export const ImageSearchModal: React.FC = ({ errorMessage, }) => { return ( - + {isLoading ? ( Analyzing image to find matches... diff --git a/src/lib/Scenes/Search/components/ResultWithHighlight.tsx b/src/lib/Scenes/Search/components/ResultWithHighlight.tsx index 25e8f415edb..e687b4c8ff1 100644 --- a/src/lib/Scenes/Search/components/ResultWithHighlight.tsx +++ b/src/lib/Scenes/Search/components/ResultWithHighlight.tsx @@ -3,7 +3,13 @@ import parse from "autosuggest-highlight/parse" import { Text } from "palette" import React from "react" -export const ResultWithHighlight = ({ displayLabel, highlight }: { displayLabel: string; highlight?: string }) => { +export const ResultWithHighlight = ({ + displayLabel, + highlight, +}: { + displayLabel: string + highlight?: string +}) => { const matches = match(displayLabel, highlight!) const parts = parse(displayLabel, matches) diff --git a/src/lib/Scenes/Search/components/SearchInput.tsx b/src/lib/Scenes/Search/components/SearchInput.tsx index e4108840a56..6d4b002339f 100644 --- a/src/lib/Scenes/Search/components/SearchInput.tsx +++ b/src/lib/Scenes/Search/components/SearchInput.tsx @@ -17,7 +17,12 @@ export interface SearchInputProps { const SEARCH_THROTTLE_INTERVAL = 500 -export const SearchInput: React.FC = ({ currentRefinement, placeholder, refine, onTextChange }) => { +export const SearchInput: React.FC = ({ + currentRefinement, + placeholder, + refine, + onTextChange, +}) => { const { trackEvent } = useTracking() const searchProviderValues = useSearchProviderValues(currentRefinement) const isImageSearchEnabled = useFeatureFlag("AREnableImageSearch") diff --git a/src/lib/Scenes/Search/components/SearchResult.tsx b/src/lib/Scenes/Search/components/SearchResult.tsx index c3b25caf74c..cb3cc28f792 100644 --- a/src/lib/Scenes/Search/components/SearchResult.tsx +++ b/src/lib/Scenes/Search/components/SearchResult.tsx @@ -13,7 +13,11 @@ interface SearchResultsItemProps { trackResultPress?: (result: AlgoliaSearchResult) => void } -export const SearchResult: React.FC = ({ result, selectedPill, trackResultPress }) => { +export const SearchResult: React.FC = ({ + result, + selectedPill, + trackResultPress, +}) => { const addArtworkToRecentSearches = () => { GlobalStore.actions.search.addRecentSearch({ type: "AUTOSUGGEST_RESULT_TAPPED", diff --git a/src/lib/Scenes/Search/components/placeholders/AlgoliaSearchPlaceholder.tsx b/src/lib/Scenes/Search/components/placeholders/AlgoliaSearchPlaceholder.tsx index c1a9af07f7d..120abd6cff5 100644 --- a/src/lib/Scenes/Search/components/placeholders/AlgoliaSearchPlaceholder.tsx +++ b/src/lib/Scenes/Search/components/placeholders/AlgoliaSearchPlaceholder.tsx @@ -8,7 +8,9 @@ interface AlgoliaSearchPlaceholderProps { hasRoundedImages: boolean } -export const AlgoliaSearchPlaceholder: React.FC = ({ hasRoundedImages }) => { +export const AlgoliaSearchPlaceholder: React.FC = ({ + hasRoundedImages, +}) => { return ( <> @@ -20,7 +22,12 @@ export const AlgoliaSearchPlaceholder: React.FC = borderRadius={hasRoundedImages ? IMAGE_SIZE / 2 : 0} /> - + ))} diff --git a/src/lib/Scenes/Search/components/placeholders/AutosuggestResultsPlaceholder.tsx b/src/lib/Scenes/Search/components/placeholders/AutosuggestResultsPlaceholder.tsx index 5f74edcb252..02e886be208 100644 --- a/src/lib/Scenes/Search/components/placeholders/AutosuggestResultsPlaceholder.tsx +++ b/src/lib/Scenes/Search/components/placeholders/AutosuggestResultsPlaceholder.tsx @@ -10,14 +10,21 @@ interface AutosuggestResultsPlaceholderProps { showResultType?: boolean } -export const AutosuggestResultsPlaceholder: React.FC = ({ showResultType }) => { +export const AutosuggestResultsPlaceholder: React.FC = ({ + showResultType, +}) => { return ( {times(20).map((index) => ( - + {!!showResultType && ( = ({ show, relay, initiallyAppliedFilter }) const artworksTotal = artworks?.counts?.total ?? 0 const artworkAggregations = (artworks?.aggregations ?? []) as aggregationsType - const setInitialFilterStateAction = ArtworksFiltersStore.useStoreActions((state) => state.setInitialFilterStateAction) - const setFilterTypeAction = ArtworksFiltersStore.useStoreActions((state) => state.setFilterTypeAction) - const setFiltersCountAction = ArtworksFiltersStore.useStoreActions((state) => state.setFiltersCountAction) + const setInitialFilterStateAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setInitialFilterStateAction + ) + const setFilterTypeAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setFilterTypeAction + ) + const setFiltersCountAction = ArtworksFiltersStore.useStoreActions( + (state) => state.setFiltersCountAction + ) const counts = ArtworksFiltersStore.useStoreState((state) => state.counts) useArtworkFilters({ diff --git a/src/lib/Scenes/Show/Components/ShowArtworksEmptyState.tsx b/src/lib/Scenes/Show/Components/ShowArtworksEmptyState.tsx index c982e2981c0..b607e7ea3c0 100644 --- a/src/lib/Scenes/Show/Components/ShowArtworksEmptyState.tsx +++ b/src/lib/Scenes/Show/Components/ShowArtworksEmptyState.tsx @@ -7,12 +7,19 @@ export interface ShowArtworksEmptyStateProps extends BoxProps { show: ShowArtworksEmptyState_show } -export const ShowArtworksEmptyState: React.FC = ({ show, ...rest }) => { +export const ShowArtworksEmptyState: React.FC = ({ + show, + ...rest +}) => { const message = [ `This ${Boolean(show.isFairBooth) ? "fair booth" : "show"} is currently unavailable.`, ...(show.status !== "closed" - ? [`Please check back closer to the ${Boolean(show.isFairBooth) ? "fair" : "show"} for artworks.`] + ? [ + `Please check back closer to the ${ + Boolean(show.isFairBooth) ? "fair" : "show" + } for artworks.`, + ] : []), ].join(" ") @@ -23,11 +30,14 @@ export const ShowArtworksEmptyState: React.FC = ({ ) } -export const ShowArtworksEmptyStateFragmentContainer = createFragmentContainer(ShowArtworksEmptyState, { - show: graphql` - fragment ShowArtworksEmptyState_show on Show { - isFairBooth - status - } - `, -}) +export const ShowArtworksEmptyStateFragmentContainer = createFragmentContainer( + ShowArtworksEmptyState, + { + show: graphql` + fragment ShowArtworksEmptyState_show on Show { + isFairBooth + status + } + `, + } +) diff --git a/src/lib/Scenes/Show/Components/ShowContextCard.tsx b/src/lib/Scenes/Show/Components/ShowContextCard.tsx index 066c56a1678..b1b31557521 100644 --- a/src/lib/Scenes/Show/Components/ShowContextCard.tsx +++ b/src/lib/Scenes/Show/Components/ShowContextCard.tsx @@ -16,7 +16,9 @@ export interface ShowContextCardProps extends BoxProps { export const ShowContextCard: React.FC = ({ show, ...rest }) => { const { isFairBooth, fair, partner } = show - const { onPress, ...card } = isFairBooth ? extractPropsFromFair(fair) : extractPropsFromPartner(partner) + const { onPress, ...card } = isFairBooth + ? extractPropsFromFair(fair) + : extractPropsFromPartner(partner) const tracking = useTracking() @@ -123,7 +125,12 @@ const ContextCard: React.FC = ({ bottom={0} left={2} > - + )} diff --git a/src/lib/Scenes/Show/Components/ShowInstallShots.tsx b/src/lib/Scenes/Show/Components/ShowInstallShots.tsx index c335c489544..e6b9fb8dcf2 100644 --- a/src/lib/Scenes/Show/Components/ShowInstallShots.tsx +++ b/src/lib/Scenes/Show/Components/ShowInstallShots.tsx @@ -30,7 +30,11 @@ export const ShowInstallShots: React.FC = ({ show, ...res return ( - + {!!image.caption && ( = ({ location: { openingHours }, ...rest }) => { +const ShowLocationHours: React.FC = ({ + location: { openingHours }, + ...rest +}) => { if (!openingHours?.text && !openingHours?.schedules) { return null } diff --git a/src/lib/Scenes/Show/Components/ShowViewingRoom.tsx b/src/lib/Scenes/Show/Components/ShowViewingRoom.tsx index 6419dea02a5..56b7f670c79 100644 --- a/src/lib/Scenes/Show/Components/ShowViewingRoom.tsx +++ b/src/lib/Scenes/Show/Components/ShowViewingRoom.tsx @@ -48,7 +48,11 @@ export const ShowViewingRoom: React.FC = ({ show, ...rest title={viewingRoom.title} subtitle={show.partner?.name ?? undefined} image={viewingRoom.image?.imageURLs?.normalized ?? ""} - tag={tagForStatus(viewingRoom.status, viewingRoom.distanceToOpen, viewingRoom.distanceToClose)} + tag={tagForStatus( + viewingRoom.status, + viewingRoom.distanceToOpen, + viewingRoom.distanceToClose + )} style={{ aspectRatio: 3 / 4 }} /> diff --git a/src/lib/Scenes/Show/Screens/ShowMoreInfo.tsx b/src/lib/Scenes/Show/Screens/ShowMoreInfo.tsx index 9418b415fd6..3de22099fe6 100644 --- a/src/lib/Scenes/Show/Screens/ShowMoreInfo.tsx +++ b/src/lib/Scenes/Show/Screens/ShowMoreInfo.tsx @@ -28,13 +28,18 @@ export interface ShowMoreInfoProps { } export const ShowMoreInfo: React.FC = ({ show }) => { - const displayablePartnerType = DISPLAYABLE_PARTNER_TYPES[show.partner?.type as keyof typeof DISPLAYABLE_PARTNER_TYPES] + const displayablePartnerType = + DISPLAYABLE_PARTNER_TYPES[show.partner?.type as keyof typeof DISPLAYABLE_PARTNER_TYPES] const location = show.location ?? show.fair?.location - const shouldDisplayPartnerType = Object.keys(DISPLAYABLE_PARTNER_TYPES).includes(show.partner?.type!) + const shouldDisplayPartnerType = Object.keys(DISPLAYABLE_PARTNER_TYPES).includes( + show.partner?.type! + ) const shouldDisplayHours = - (location?.openingHours?.__typename === "OpeningHoursArray" && !!location.openingHours.schedules) || + (location?.openingHours?.__typename === "OpeningHoursArray" && + !!location.openingHours.schedules) || (location?.openingHours?.__typename === "OpeningHoursText" && !!location.openingHours.text) - const shouldDisplayLocation = !!show.partner && !!location?.coordinates?.lat && !!location?.coordinates?.lng + const shouldDisplayLocation = + !!show.partner && !!location?.coordinates?.lat && !!location?.coordinates?.lng const sections: Section[] = [ { diff --git a/src/lib/Scenes/Show/Show.tests.tsx b/src/lib/Scenes/Show/Show.tests.tsx index d99c6557171..ca03a7ab2dd 100644 --- a/src/lib/Scenes/Show/Show.tests.tsx +++ b/src/lib/Scenes/Show/Show.tests.tsx @@ -42,7 +42,9 @@ describe("Show", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Show/Show.tsx b/src/lib/Scenes/Show/Show.tsx index e21d46c9dce..419d58abb7d 100644 --- a/src/lib/Scenes/Show/Show.tsx +++ b/src/lib/Scenes/Show/Show.tsx @@ -61,7 +61,9 @@ export const Show: React.FC = ({ show }) => { const sections: Section[] = [ { key: "header", element: }, - ...(Boolean(show.images?.length) ? [{ key: "install-shots", element: }] : []), + ...(Boolean(show.images?.length) + ? [{ key: "install-shots", element: }] + : []), { key: "info", element: }, @@ -70,7 +72,10 @@ export const Show: React.FC = ({ show }) => { element: ( - + ), }, @@ -118,11 +123,17 @@ export const Show: React.FC = ({ show }) => { ListHeaderComponent={} ListFooterComponent={} ItemSeparatorComponent={() => } - contentContainerStyle={{ paddingTop: useScreenDimensions().safeAreaInsets.top, paddingBottom: 40 }} + contentContainerStyle={{ + paddingTop: useScreenDimensions().safeAreaInsets.top, + paddingBottom: 40, + }} renderItem={({ item: { element } }) => element} - onScroll={Animated.event([{ nativeEvent: { contentOffset: { y: filterComponentAnimationValue } } }], { - useNativeDriver: true, - })} + onScroll={Animated.event( + [{ nativeEvent: { contentOffset: { y: filterComponentAnimationValue } } }], + { + useNativeDriver: true, + } + )} /> diff --git a/src/lib/Scenes/Show/ShowArtworks.tests.tsx b/src/lib/Scenes/Show/ShowArtworks.tests.tsx index 0c8258c61b3..c3f3df92d91 100644 --- a/src/lib/Scenes/Show/ShowArtworks.tests.tsx +++ b/src/lib/Scenes/Show/ShowArtworks.tests.tsx @@ -42,7 +42,9 @@ describe("ShowArtworks", () => { /> ) - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) return tree } diff --git a/src/lib/Scenes/Show/ShowArtworksEmptyState.tests.tsx b/src/lib/Scenes/Show/ShowArtworksEmptyState.tests.tsx index 18371b6dd30..586baa5f894 100644 --- a/src/lib/Scenes/Show/ShowArtworksEmptyState.tests.tsx +++ b/src/lib/Scenes/Show/ShowArtworksEmptyState.tests.tsx @@ -40,7 +40,9 @@ describe("ShowArtworksEmptyState", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -71,7 +73,9 @@ describe("ShowArtworksEmptyState", () => { const wrapper = getWrapper({ Show: () => ({ isFairBooth: false }) }) const text = extractText(wrapper.root) - expect(text).toContain("This show is currently unavailable. Please check back closer to the show for artworks.") + expect(text).toContain( + "This show is currently unavailable. Please check back closer to the show for artworks." + ) }) it("renders the correct message for closed shows", () => { diff --git a/src/lib/Scenes/Show/ShowContextCard.tests.tsx b/src/lib/Scenes/Show/ShowContextCard.tests.tsx index 2cb881352fa..b228ff41d0e 100644 --- a/src/lib/Scenes/Show/ShowContextCard.tests.tsx +++ b/src/lib/Scenes/Show/ShowContextCard.tests.tsx @@ -45,7 +45,9 @@ describe("ShowContextCard", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -77,7 +79,9 @@ describe("ShowContextCard", () => { expect(text).toMatch("Part of IFPDA Print Fair 2020") expect(text).toMatch("Jan 1 - Jan 31") - const renderedImages = wrapper.root.findAllByType(OpaqueImageView).map((img) => img.props.imageURL) + const renderedImages = wrapper.root + .findAllByType(OpaqueImageView) + .map((img) => img.props.imageURL) expect(renderedImages).toContain("http://test.artsy.net/fair-logo.jpg") expect(renderedImages).toContain("http://test.artsy.net/fair-main.jpg") }) @@ -151,7 +155,9 @@ describe("ShowContextCard", () => { expect(text).toMatch("Presented by Pace Prints") expect(text).toMatch("New York, London") - const renderedImages = wrapper.root.findAllByType(OpaqueImageView).map((img) => img.props.imageURL) + const renderedImages = wrapper.root + .findAllByType(OpaqueImageView) + .map((img) => img.props.imageURL) expect(renderedImages).toContain("http://test.artsy.net/artwork-1.jpg") expect(renderedImages).toContain("http://test.artsy.net/artwork-2.jpg") expect(renderedImages).toContain("http://test.artsy.net/artwork-3.jpg") diff --git a/src/lib/Scenes/Show/ShowHours.tests.tsx b/src/lib/Scenes/Show/ShowHours.tests.tsx index 83260a39c91..6b56f3afc2d 100644 --- a/src/lib/Scenes/Show/ShowHours.tests.tsx +++ b/src/lib/Scenes/Show/ShowHours.tests.tsx @@ -40,7 +40,9 @@ describe("ShowHours", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Show/ShowLocation.tests.tsx b/src/lib/Scenes/Show/ShowLocation.tests.tsx index f9a28611eb0..ae0f18dd9d1 100644 --- a/src/lib/Scenes/Show/ShowLocation.tests.tsx +++ b/src/lib/Scenes/Show/ShowLocation.tests.tsx @@ -64,7 +64,9 @@ describe("ShowLocation", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Show/ShowMoreInfo.tests.tsx b/src/lib/Scenes/Show/ShowMoreInfo.tests.tsx index fced27531c4..159611dd292 100644 --- a/src/lib/Scenes/Show/ShowMoreInfo.tests.tsx +++ b/src/lib/Scenes/Show/ShowMoreInfo.tests.tsx @@ -42,7 +42,9 @@ describe("ShowMoreInfo", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } diff --git a/src/lib/Scenes/Show/ShowViewingRoom.tests.tsx b/src/lib/Scenes/Show/ShowViewingRoom.tests.tsx index 7def59864b1..f89abb5f898 100644 --- a/src/lib/Scenes/Show/ShowViewingRoom.tests.tsx +++ b/src/lib/Scenes/Show/ShowViewingRoom.tests.tsx @@ -42,7 +42,9 @@ describe("ShowViewingRoom", () => { const getWrapper = (mockResolvers = {}) => { const tree = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return tree } @@ -62,7 +64,10 @@ describe("ShowViewingRoom", () => { it("tracks taps", () => { const wrapper = getWrapper({ Show: () => ({ internalID: "example-show-id", slug: "example-slug" }), - ViewingRoom: () => ({ internalID: "example-viewing-room-id", slug: "example-viewing-room-slug" }), + ViewingRoom: () => ({ + internalID: "example-viewing-room-id", + slug: "example-viewing-room-slug", + }), }) act(() => { diff --git a/src/lib/Scenes/Tag/Tag.tsx b/src/lib/Scenes/Tag/Tag.tsx index b017bfceda5..8e922d3b42d 100644 --- a/src/lib/Scenes/Tag/Tag.tsx +++ b/src/lib/Scenes/Tag/Tag.tsx @@ -74,7 +74,11 @@ export const Tag: React.FC = (props) => { }} > - + ) diff --git a/src/lib/Scenes/VanityURL/VanityURLEntity.tests.tsx b/src/lib/Scenes/VanityURL/VanityURLEntity.tests.tsx index 0bf23b7aa8f..3cdfdc011b9 100644 --- a/src/lib/Scenes/VanityURL/VanityURLEntity.tests.tsx +++ b/src/lib/Scenes/VanityURL/VanityURLEntity.tests.tsx @@ -46,7 +46,9 @@ describe("VanityURLEntity", () => { }) it("renders a fairQueryRenderer when given a fair id", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("FairQuery") act(() => { env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation)) @@ -57,26 +59,36 @@ describe("VanityURLEntity", () => { describe("rendering a profile", () => { it("shows a fair placeholder when entityType is fair", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const fairPlaceholder = tree.root.findByType(FairPlaceholder) expect(fairPlaceholder).toBeDefined() }) it("shows a partner placeholder when entityType is partner", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const partnerPlaceholder = tree.root.findByType(HeaderTabsGridPlaceholder) expect(partnerPlaceholder).toBeDefined() }) it("shows a spinner when entityType is unknown", () => { - const tree = renderWithWrappers() + const tree = renderWithWrappers( + + ) const spinner = tree.root.findByType(Spinner) expect(spinner).toBeDefined() }) it("renders a partner when a partner is returned", () => { - const tree = renderWithWrappers() - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("VanityURLEntityQuery") + const tree = renderWithWrappers( + + ) + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "VanityURLEntityQuery" + ) act(() => { env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, { @@ -95,8 +107,12 @@ describe("VanityURLEntity", () => { // TODO: Passes in isolation, but not with other specs xit("renders a fair when a fair is returned", () => { - const tree = renderWithWrappers() - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("VanityURLEntityQuery") + const tree = renderWithWrappers( + + ) + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "VanityURLEntityQuery" + ) act(() => { env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, { @@ -113,8 +129,12 @@ describe("VanityURLEntity", () => { }) it("renders a webview when an unknown profile type is returned", () => { - const tree = renderWithWrappers() - expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe("VanityURLEntityQuery") + const tree = renderWithWrappers( + + ) + expect(env.mock.getMostRecentOperation().request.node.operation.name).toBe( + "VanityURLEntityQuery" + ) act(() => { env.mock.resolveMostRecentOperation({ errors: [], diff --git a/src/lib/Scenes/VanityURL/VanityURLEntity.tsx b/src/lib/Scenes/VanityURL/VanityURLEntity.tsx index ebdb2a00c3e..517f871b4ae 100644 --- a/src/lib/Scenes/VanityURL/VanityURLEntity.tsx +++ b/src/lib/Scenes/VanityURL/VanityURLEntity.tsx @@ -83,14 +83,24 @@ export const VanityURLEntityRenderer: React.FC = ({ entity, slugT ) default: return ( - + ) } }, render: (props: any) => { - return + return ( + + ) }, })} /> diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tests.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tests.tsx index e93bdd680e1..74e69a63e1e 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tests.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tests.tsx @@ -58,7 +58,10 @@ describe("ViewingRoomArtworkRail", () => { expect(navigate).toHaveBeenCalledWith("/viewing-room/gallery-name-viewing-room-name/artworks") expect(postEventToProviders).toHaveBeenCalledWith( - tracks.tappedArtworkGroupHeader("2955ab33-c205-44ea-93d2-514cd7ee2bcd", "gallery-name-viewing-room-name") + tracks.tappedArtworkGroupHeader( + "2955ab33-c205-44ea-93d2-514cd7ee2bcd", + "gallery-name-viewing-room-name" + ) ) }) @@ -76,7 +79,8 @@ describe("ViewingRoomArtworkRail", () => { slug: "nicolas-party-rocks-ii", artistNames: ["Nicolas Party"], image: { - imageURL: "https://d32dm0rphc51dk.cloudfront.net/Tc9k2ROn55SxNHWjYxxnrg/:version.jpg", + imageURL: + "https://d32dm0rphc51dk.cloudfront.net/Tc9k2ROn55SxNHWjYxxnrg/:version.jpg", }, saleMessage: "$20,000", }, @@ -89,7 +93,8 @@ describe("ViewingRoomArtworkRail", () => { href: "/artwork/nicolas-party-still-life-no-011", saleMessage: "$25,000", image: { - imageURL: "https://d32dm0rphc51dk.cloudfront.net/Tc9k2ROn55SxNHWjYxxnrg/:version.jpg", + imageURL: + "https://d32dm0rphc51dk.cloudfront.net/Tc9k2ROn55SxNHWjYxxnrg/:version.jpg", }, }, }, diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tsx index 980e64a75a2..59832bb1534 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomArtworkRail.tsx @@ -28,7 +28,9 @@ export const ViewingRoomArtworkRail: React.FC = ({ { - tracking.trackEvent(tracks.tappedArtworkGroupHeader(viewingRoom.internalID, viewingRoom.slug)) + tracking.trackEvent( + tracks.tappedArtworkGroupHeader(viewingRoom.internalID, viewingRoom.slug) + ) navigate(`/viewing-room/${viewingRoom.slug}/artworks`) }} /> @@ -37,7 +39,12 @@ export const ViewingRoomArtworkRail: React.FC = ({ artworks={artworks} onPress={(artwork) => { tracking.trackEvent( - tracks.tappedArtworkThumbnail(viewingRoom.internalID, viewingRoom.slug, artwork.internalID, artwork.slug) + tracks.tappedArtworkThumbnail( + viewingRoom.internalID, + viewingRoom.slug, + artwork.internalID, + artwork.slug + ) ) navigate(`/viewing-room/${viewingRoom.slug}/${artwork.slug}`) }} @@ -61,7 +68,12 @@ export const tracks = { type: "header", } }, - tappedArtworkThumbnail: (vrId: string, vrSlug: string, artworkId: string, artworkSlug: string) => ({ + tappedArtworkThumbnail: ( + vrId: string, + vrSlug: string, + artworkId: string, + artworkSlug: string + ) => ({ action: Schema.ActionNames.TappedArtworkGroup, context_module: Schema.ContextModules.ViewingRoomArtworkRail, context_screen_owner_type: Schema.OwnerEntityTypes.ViewingRoom, diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tests.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tests.tsx index dfab4e97e0b..14e000938ab 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tests.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tests.tsx @@ -103,7 +103,9 @@ describe("ViewingRoomHeader", () => { }) return result }) - expect(tree.root.findByProps({ testID: "partner-icon" }).props.source.uri).toBe("https://example.com/image.jpg") + expect(tree.root.findByProps({ testID: "partner-icon" }).props.source.uri).toBe( + "https://example.com/image.jpg" + ) }) it("doesn't render logo (and doesn't crash) if partner profile is null", () => { diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tsx index 7e5f3988913..f98581b760c 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomHeader.tsx @@ -48,13 +48,19 @@ const CountdownText: React.FC = ({ duration }) => { return ( {sections - .map(({ time, label }, idx) => (idx < sections.length - 1 ? time + label + separator : time + label)) + .map(({ time, label }, idx) => + idx < sections.length - 1 ? time + label + separator : time + label + ) .join("")} ) } -const Countdown: React.FC<{ startAt: string; endAt: string; status: string }> = ({ startAt, endAt, status }) => { +const Countdown: React.FC<{ startAt: string; endAt: string; status: string }> = ({ + startAt, + endAt, + status, +}) => { let finalText = "" if (status === ViewingRoomStatus.CLOSED) { finalText = "Closed" diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomSubsections.tests.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomSubsections.tests.tsx index 822cd41927e..de22d64d0d0 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomSubsections.tests.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomSubsections.tests.tsx @@ -32,6 +32,8 @@ describe("ViewingRoomSubsections", () => { const tree = renderWithWrappers() mockEnvironmentPayload(mockEnvironment) - expect(tree.root.findAllByType(Box).filter((box) => box.props.testID === "subsection")).toHaveLength(1) + expect( + tree.root.findAllByType(Box).filter((box) => box.props.testID === "subsection") + ).toHaveLength(1) }) }) diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tests.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tests.tsx index fd8903cb75c..22c586be0e8 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tests.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tests.tsx @@ -49,7 +49,10 @@ describe("ViewingRoomViewWorksButton", () => { expect(navigate).toHaveBeenCalledWith("/viewing-room/gallery-name-viewing-room-name/artworks") expect(useTracking().trackEvent).toHaveBeenCalledWith( - tracks.tappedViewWorksButton("2955ab33-c205-44ea-93d2-514cd7ee2bcd", "gallery-name-viewing-room-name") + tracks.tappedViewWorksButton( + "2955ab33-c205-44ea-93d2-514cd7ee2bcd", + "gallery-name-viewing-room-name" + ) ) }) }) diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tsx index d30c24196dd..8f773f0e407 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomViewWorksButton.tsx @@ -34,7 +34,9 @@ export const ViewingRoomViewWorksButton: React.FC { - tracking.trackEvent(tracks.tappedViewWorksButton(viewingRoom.internalID, viewingRoom.slug)) + tracking.trackEvent( + tracks.tappedViewWorksButton(viewingRoom.internalID, viewingRoom.slug) + ) navigate(`/viewing-room/${viewingRoom.slug}/artworks`) }} > @@ -71,14 +73,17 @@ export const tracks = { }, } -export const ViewingRoomViewWorksButtonContainer = createFragmentContainer(ViewingRoomViewWorksButton, { - viewingRoom: graphql` - fragment ViewingRoomViewWorksButton_viewingRoom on ViewingRoom { - slug - internalID - artworksForCount: artworksConnection(first: 1) { - totalCount +export const ViewingRoomViewWorksButtonContainer = createFragmentContainer( + ViewingRoomViewWorksButton, + { + viewingRoom: graphql` + fragment ViewingRoomViewWorksButton_viewingRoom on ViewingRoom { + slug + internalID + artworksForCount: artworksConnection(first: 1) { + totalCount + } } - } - `, -}) + `, + } +) diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsHomeRail.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsHomeRail.tsx index 05dafa530ac..edfb5a4bbe1 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsHomeRail.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsHomeRail.tsx @@ -11,7 +11,11 @@ import React, { Suspense } from "react" import { FlatList } from "react-native" import { graphql, useFragment, useLazyLoadQuery } from "react-relay" import { useTracking } from "react-tracking" -import { featuredFragment, FeaturedRail, tracks as featuredTracks } from "./ViewingRoomsListFeatured" +import { + featuredFragment, + FeaturedRail, + tracks as featuredTracks, +} from "./ViewingRoomsListFeatured" import { tagForStatus } from "./ViewingRoomsListItem" interface ViewingRoomsHomeMainRailProps { @@ -20,7 +24,11 @@ interface ViewingRoomsHomeMainRailProps { mb?: number } -export const ViewingRoomsHomeMainRail: React.FC = ({ featured, title, mb }) => { +export const ViewingRoomsHomeMainRail: React.FC = ({ + featured, + title, + mb, +}) => { const { trackEvent } = useTracking() const featuredData = useFragment(featuredFragment, featured) diff --git a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsListItem.tsx b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsListItem.tsx index 074c69b83b7..e37919bf506 100644 --- a/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsListItem.tsx +++ b/src/lib/Scenes/ViewingRoom/Components/ViewingRoomsListItem.tsx @@ -92,7 +92,12 @@ export const ViewingRoomsListItem: React.FC = (props) navigate(`/viewing-room/${slug!}`) }} > - + ) diff --git a/src/lib/Scenes/ViewingRoom/ViewingRoom.tests.tsx b/src/lib/Scenes/ViewingRoom/ViewingRoom.tests.tsx index 3d876399a92..c809497176d 100644 --- a/src/lib/Scenes/ViewingRoom/ViewingRoom.tests.tsx +++ b/src/lib/Scenes/ViewingRoom/ViewingRoom.tests.tsx @@ -135,12 +135,17 @@ describe("ViewingRoom", () => { expect(tree.root.findAllByType(AnimatedBottomButton)[0].props.isVisible).toBe(false) act(() => { - tree.root.findByType(FlatList).props.onViewableItemsChanged({ viewableItems: [{ item: { key: "body" } }] }) + tree.root + .findByType(FlatList) + .props.onViewableItemsChanged({ viewableItems: [{ item: { key: "body" } }] }) }) expect(tree.root.findAllByType(AnimatedBottomButton)[0].props.isVisible).toBe(true) expect(useTracking().trackEvent).toHaveBeenCalledWith( - tracks.bodyImpression("2955ab33-c205-44ea-93d2-514cd7ee2bcd", "gallery-name-viewing-room-name") + tracks.bodyImpression( + "2955ab33-c205-44ea-93d2-514cd7ee2bcd", + "gallery-name-viewing-room-name" + ) ) }) }) diff --git a/src/lib/Scenes/ViewingRoom/ViewingRoom.tsx b/src/lib/Scenes/ViewingRoom/ViewingRoom.tsx index 93e6955c1d2..882cdf68549 100644 --- a/src/lib/Scenes/ViewingRoom/ViewingRoom.tsx +++ b/src/lib/Scenes/ViewingRoom/ViewingRoom.tsx @@ -9,7 +9,14 @@ import { once } from "lodash" import { Box, Button, Flex, Sans, ShareIcon, Spacer, Text } from "palette" import { _maxWidth as maxWidth } from "palette" import React, { useCallback, useState } from "react" -import { FlatList, LayoutAnimation, Share, TouchableWithoutFeedback, View, ViewToken } from "react-native" +import { + FlatList, + LayoutAnimation, + Share, + TouchableWithoutFeedback, + View, + ViewToken, +} from "react-native" import { createFragmentContainer, graphql, QueryRenderer } from "react-relay" import { useTracking } from "react-tracking" import styled from "styled-components/native" @@ -35,12 +42,17 @@ export enum ViewingRoomStatus { CLOSED = "closed", } -export const ClosedNotice: React.FC<{ status: string; partnerHref: string }> = ({ status, partnerHref }) => { +export const ClosedNotice: React.FC<{ status: string; partnerHref: string }> = ({ + status, + partnerHref, +}) => { let finalText = "" if (status === ViewingRoomStatus.CLOSED) { - finalText = "This viewing room is now closed. We invite you to view this gallery’s current works." + finalText = + "This viewing room is now closed. We invite you to view this gallery’s current works." } else if (status === ViewingRoomStatus.SCHEDULED) { - finalText = "This viewing room is not yet open. We invite you to view this gallery’s current works." + finalText = + "This viewing room is not yet open. We invite you to view this gallery’s current works." } return ( @@ -60,10 +72,13 @@ export const ViewingRoom: React.FC = (props) => { const [displayViewWorksButton, setDisplayViewWorksButton] = useState(false) const tracking = useTracking() const trackBodyImpression = useCallback( - once(() => tracking.trackEvent(tracks.bodyImpression(viewingRoom.internalID, viewingRoom.slug))), + once(() => + tracking.trackEvent(tracks.bodyImpression(viewingRoom.internalID, viewingRoom.slug)) + ), [] ) - const trackShare = () => tracking.trackEvent(tracks.share(viewingRoom.internalID, viewingRoom.slug)) + const trackShare = () => + tracking.trackEvent(tracks.share(viewingRoom.internalID, viewingRoom.slug)) async function handleViewingRoomShare() { trackShare() try { @@ -79,10 +94,15 @@ export const ViewingRoom: React.FC = (props) => { const sections: ViewingRoomSection[] = [] - if (viewingRoom.status === ViewingRoomStatus.CLOSED || viewingRoom.status === ViewingRoomStatus.SCHEDULED) { + if ( + viewingRoom.status === ViewingRoomStatus.CLOSED || + viewingRoom.status === ViewingRoomStatus.SCHEDULED + ) { sections.push({ key: "closedNotice", - content: , + content: ( + + ), }) } else if (viewingRoom.status === ViewingRoomStatus.LIVE) { sections.push({ @@ -164,7 +184,10 @@ export const ViewingRoom: React.FC = (props) => { onViewableItemsChanged={useCallback(({ viewableItems }) => { if (viewableItems.find((viewableItem: ViewToken) => viewableItem.item.key === "body")) { trackBodyImpression() - LayoutAnimation.configureNext({ ...LayoutAnimation.Presets.easeInEaseOut, duration: 150 }) + LayoutAnimation.configureNext({ + ...LayoutAnimation.Presets.easeInEaseOut, + duration: 150, + }) setDisplayViewWorksButton(true) } }, [])} @@ -232,7 +255,9 @@ export const ViewingRoomFragmentContainer = createFragmentContainer(ViewingRoom, `, }) -export const ViewingRoomQueryRenderer: React.FC<{ viewing_room_id: string }> = ({ viewing_room_id: viewingRoomID }) => { +export const ViewingRoomQueryRenderer: React.FC<{ viewing_room_id: string }> = ({ + viewing_room_id: viewingRoomID, +}) => { return ( environment={defaultEnvironment} diff --git a/src/lib/Scenes/ViewingRoom/ViewingRoomArtwork.tsx b/src/lib/Scenes/ViewingRoom/ViewingRoomArtwork.tsx index 9c3d56e16a0..7da3feabf43 100644 --- a/src/lib/Scenes/ViewingRoom/ViewingRoomArtwork.tsx +++ b/src/lib/Scenes/ViewingRoom/ViewingRoomArtwork.tsx @@ -5,7 +5,18 @@ import { PlaceholderBox, PlaceholderText, ProvidePlaceholderContext } from "lib/ import { ProvideScreenTracking, Schema } from "lib/utils/track" import { useScreenDimensions } from "lib/utils/useScreenDimensions" import _ from "lodash" -import { Box, Button, EyeOpenedIcon, Flex, LargeCard, Sans, Separator, Spacer, Text, Touchable } from "palette" +import { + Box, + Button, + EyeOpenedIcon, + Flex, + LargeCard, + Sans, + Separator, + Spacer, + Text, + Touchable, +} from "palette" import React, { Suspense, useEffect } from "react" import { FlatList, ScrollView, TouchableWithoutFeedback } from "react-native" import { useTracking } from "react-tracking" @@ -13,7 +24,13 @@ import { useTracking } from "react-tracking" import { ViewingRoomArtwork_selectedArtwork$key } from "__generated__/ViewingRoomArtwork_selectedArtwork.graphql" import { ViewingRoomArtwork_viewingRoomInfo$key } from "__generated__/ViewingRoomArtwork_viewingRoomInfo.graphql" import { ViewingRoomArtworkQuery } from "__generated__/ViewingRoomArtworkQuery.graphql" -import { graphql, PreloadedQuery, useFragment, usePreloadedQuery, useQueryLoader } from "react-relay" +import { + graphql, + PreloadedQuery, + useFragment, + usePreloadedQuery, + useQueryLoader, +} from "react-relay" import { ImageCarousel } from "../Artwork/Components/ImageCarousel/ImageCarousel" import { tagForStatus } from "./Components/ViewingRoomsListItem" @@ -57,7 +74,9 @@ export const ViewingRoomArtwork: React.FC = (props) => - {!!(LegacyNativeModules.ARCocoaConstantsModule.AREnabled && selectedArtwork.isHangable) && ( + {!!( + LegacyNativeModules.ARCocoaConstantsModule.AREnabled && selectedArtwork.isHangable + ) && ( = (props) => variant="fillDark" block onPress={() => { - trackEvent(tracks.tap(vrInfo.internalID, vrInfo.slug, selectedArtwork.id, selectedArtwork.slug)) + trackEvent( + tracks.tap(vrInfo.internalID, vrInfo.slug, selectedArtwork.id, selectedArtwork.slug) + ) navigate(selectedArtwork.href!) }} > @@ -119,7 +140,9 @@ export const ViewingRoomArtwork: React.FC = (props) => `${index}`} - renderItem={({ item }) => } + renderItem={({ item }) => ( + + )} ItemSeparatorComponent={() => } /> @@ -145,7 +168,9 @@ export const ViewingRoomArtwork: React.FC = (props) => ) } -export const ViewingRoomArtworkContainer: React.FC = ({ queryRef }) => { +export const ViewingRoomArtworkContainer: React.FC = ({ + queryRef, +}) => { const data = usePreloadedQuery(ViewingRoomArtworkScreenQuery, queryRef) if (!data.artwork || !data.viewingRoom) { @@ -167,11 +192,13 @@ const ViewingRoomArtworkScreenQuery = graphql` } ` -export const ViewingRoomArtworkScreen: React.FC<{ viewing_room_id: string; artwork_id: string }> = ({ - viewing_room_id: viewingRoomID, - artwork_id: artworkID, -}) => { - const [queryRef, loadQuery] = useQueryLoader(ViewingRoomArtworkScreenQuery) +export const ViewingRoomArtworkScreen: React.FC<{ + viewing_room_id: string + artwork_id: string +}> = ({ viewing_room_id: viewingRoomID, artwork_id: artworkID }) => { + const [queryRef, loadQuery] = useQueryLoader( + ViewingRoomArtworkScreenQuery + ) useEffect(() => { if (!queryRef) { diff --git a/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tests.tsx b/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tests.tsx index d376ea2c2ac..f06909c7a53 100644 --- a/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tests.tsx +++ b/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tests.tsx @@ -52,9 +52,9 @@ describe("ViewingRoom", () => { }), }) - expect(extractText(tree.root.findByProps({ testID: "artwork-additional-information" }))).toEqual( - "additionalInformation-1" - ) + expect( + extractText(tree.root.findByProps({ testID: "artwork-additional-information" })) + ).toEqual("additionalInformation-1") }) it("navigates to artwork screen + calls tracking on press", () => { diff --git a/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tsx b/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tsx index b7f75ced21b..87b07c7902a 100644 --- a/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tsx +++ b/src/lib/Scenes/ViewingRoom/ViewingRoomArtworks.tsx @@ -124,7 +124,12 @@ export const tracks = { context_screen_owner_id: viewingRoomID, context_screen_owner_slug: viewingRoomSlug, }), - tappedArtworkGroup: (viewingRoomID: string, viewingRoomSlug: string, artworkID: string, artworkSlug: string) => ({ + tappedArtworkGroup: ( + viewingRoomID: string, + viewingRoomSlug: string, + artworkID: string, + artworkSlug: string + ) => ({ action: Schema.ActionNames.TappedArtworkGroup, context_module: Schema.ContextModules.ArtworkGrid, destination_screen: Schema.PageNames.ViewingRoomArtworkPage, @@ -141,10 +146,14 @@ export const ViewingRoomArtworksContainer = createPaginationContainer( { viewingRoom: graphql` fragment ViewingRoomArtworks_viewingRoom on ViewingRoom - @argumentDefinitions(count: { type: "Int", defaultValue: 5 }, cursor: { type: "String", defaultValue: "" }) { + @argumentDefinitions( + count: { type: "Int", defaultValue: 5 } + cursor: { type: "String", defaultValue: "" } + ) { internalID slug - artworksConnection(first: $count, after: $cursor) @connection(key: "ViewingRoomArtworks_artworksConnection") { + artworksConnection(first: $count, after: $cursor) + @connection(key: "ViewingRoomArtworks_artworksConnection") { edges { node { additionalInformation diff --git a/src/lib/Scenes/ViewingRoom/ViewingRoomsList.tsx b/src/lib/Scenes/ViewingRoom/ViewingRoomsList.tsx index 939688edbc8..1381335e314 100644 --- a/src/lib/Scenes/ViewingRoom/ViewingRoomsList.tsx +++ b/src/lib/Scenes/ViewingRoom/ViewingRoomsList.tsx @@ -57,7 +57,10 @@ const useNumColumns = () => { } export const ViewingRoomsList: FC = () => { - const queryData = useLazyLoadQuery(ViewingRoomsListScreenQuery, viewingRoomsDefaultVariables) + const queryData = useLazyLoadQuery( + ViewingRoomsListScreenQuery, + viewingRoomsDefaultVariables + ) const space = useSpace() const { data, isLoadingNext, hasNext, loadNext, refetch } = usePaginationFragment< @@ -66,7 +69,10 @@ export const ViewingRoomsList: FC = () => { >(fragmentSpec, queryData) const viewingRooms = extractNodes(data.viewingRooms) - const featuredData = useFragment(featuredFragment, queryData.featured!) + const featuredData = useFragment( + featuredFragment, + queryData.featured! + ) const featuredLength = extractNodes(featuredData).length const handleLoadMore = () => { @@ -129,8 +135,16 @@ export const ViewingRoomsList: FC = () => { - {/* right side separator*/ index % numColumns < numColumns - 1 && } - {/* right list padding */ index % numColumns === numColumns - 1 && } + { + /* right side separator*/ index % numColumns < numColumns - 1 && ( + + ) + } + { + /* right list padding */ index % numColumns === numColumns - 1 && ( + + ) + } ) } @@ -138,7 +152,9 @@ export const ViewingRoomsList: FC = () => { ItemSeparatorComponent={() => } onEndReached={handleLoadMore} onEndReachedThreshold={1} - ListFooterComponent={() => (hasNext ? : )} + ListFooterComponent={() => + hasNext ? : + } /> diff --git a/src/lib/__fixtures__/CityFixture.ts b/src/lib/__fixtures__/CityFixture.ts index c67bc68f484..50a99b447ac 100644 --- a/src/lib/__fixtures__/CityFixture.ts +++ b/src/lib/__fixtures__/CityFixture.ts @@ -416,7 +416,8 @@ export const CityFixture = { end_at: "2004-03-20T23:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-perrotin-gianni-motti-plausible-deniability-at-migros-museum-fur-gegenwartskunst-zurich", + gravityID: + "galerie-perrotin-gianni-motti-plausible-deniability-at-migros-museum-fur-gegenwartskunst-zurich", id: "U2hvdzpnYWxlcmllLXBlcnJvdGluLWdpYW5uaS1tb3R0aS1wbGF1c2libGUtZGVuaWFiaWxpdHktYXQtbWlncm9zLW11c2V1bS1mdXItZ2VnZW53YXJ0c2t1bnN0LXp1cmljaA==", is_followed: true, isStubShow: false, @@ -676,7 +677,8 @@ export const CityFixture = { end_at: "2007-11-10T23:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-perrotin-aya-takano-tradition-and-modernity-at-fondation-joan-miro-barcelona", + gravityID: + "galerie-perrotin-aya-takano-tradition-and-modernity-at-fondation-joan-miro-barcelona", id: "U2hvdzpnYWxlcmllLXBlcnJvdGluLWF5YS10YWthbm8tdHJhZGl0aW9uLWFuZC1tb2Rlcm5pdHktYXQtZm9uZGF0aW9uLWpvYW4tbWlyby1iYXJjZWxvbmE=", is_followed: true, isStubShow: false, @@ -750,7 +752,8 @@ export const CityFixture = { end_at: "2008-04-19T22:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-perrotin-gelitin-la-louvre-paris-at-musee-dart-moderne-de-la-ville-de-paris", + gravityID: + "galerie-perrotin-gelitin-la-louvre-paris-at-musee-dart-moderne-de-la-ville-de-paris", id: "U2hvdzpnYWxlcmllLXBlcnJvdGluLWdlbGl0aW4tbGEtbG91dnJlLXBhcmlzLWF0LW11c2VlLWRhcnQtbW9kZXJuZS1kZS1sYS12aWxsZS1kZS1wYXJpcw==", is_followed: true, isStubShow: false, @@ -898,7 +901,8 @@ export const CityFixture = { end_at: "2010-03-14T12:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-jacob-paulett-hotel-normandy-deauville-for-international-asian-film-festival", + gravityID: + "galerie-jacob-paulett-hotel-normandy-deauville-for-international-asian-film-festival", id: "U2hvdzpnYWxlcmllLWphY29iLXBhdWxldHQtaG90ZWwtbm9ybWFuZHktZGVhdXZpbGxlLWZvci1pbnRlcm5hdGlvbmFsLWFzaWFuLWZpbG0tZmVzdGl2YWw=", is_followed: true, isStubShow: false, @@ -935,7 +939,8 @@ export const CityFixture = { end_at: "2010-09-25T22:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-perrotin-sophie-calle-talking-to-strangers-at-louisiana-museum-copenhagen", + gravityID: + "galerie-perrotin-sophie-calle-talking-to-strangers-at-louisiana-museum-copenhagen", id: "U2hvdzpnYWxlcmllLXBlcnJvdGluLXNvcGhpZS1jYWxsZS10YWxraW5nLXRvLXN0cmFuZ2Vycy1hdC1sb3Vpc2lhbmEtbXVzZXVtLWNvcGVuaGFnZW4=", is_followed: true, isStubShow: false, @@ -1751,7 +1756,8 @@ export const CityFixture = { end_at: "2012-08-25T22:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-perrotin-paola-pivi-how-i-roll-at-doris-c-freedman-plaza-central-park-new-york", + gravityID: + "galerie-perrotin-paola-pivi-how-i-roll-at-doris-c-freedman-plaza-central-park-new-york", id: "U2hvdzpnYWxlcmllLXBlcnJvdGluLXBhb2xhLXBpdmktaG93LWktcm9sbC1hdC1kb3Jpcy1jLWZyZWVkbWFuLXBsYXphLWNlbnRyYWwtcGFyay1uZXcteW9yaw==", is_followed: true, isStubShow: false, @@ -2243,7 +2249,8 @@ export const CityFixture = { end_at: "2002-03-31T22:00:00+00:00", exhibition_period: "Mar 21 – May 25", href: "https://wwww.show.com", - gravityID: "galerie-perrotin-gianni-motti-cadeaux-diplomatiques-at-kunstmuseum-thun-thun", + gravityID: + "galerie-perrotin-gianni-motti-cadeaux-diplomatiques-at-kunstmuseum-thun-thun", id: "U2hvdzpnYWxlcmllLXBlcnJvdGluLWdpYW5uaS1tb3R0aS1jYWRlYXV4LWRpcGxvbWF0aXF1ZXMtYXQta3Vuc3RtdXNldW0tdGh1bi10aHVu", is_followed: true, isStubShow: false, diff --git a/src/lib/navigation/BackButton.tsx b/src/lib/navigation/BackButton.tsx index 4c5579f1464..5a09888f98d 100644 --- a/src/lib/navigation/BackButton.tsx +++ b/src/lib/navigation/BackButton.tsx @@ -6,11 +6,11 @@ import { TouchableOpacity } from "react-native" import { useFirstMountState } from "react-use/esm/useFirstMountState" import { goBack } from "./navigate" -export const BackButton: React.FC<{ show?: boolean; showCloseIcon?: boolean; onPress?(): void }> = ({ - onPress = goBack, - show = true, - showCloseIcon = false, -}) => { +export const BackButton: React.FC<{ + show?: boolean + showCloseIcon?: boolean + onPress?(): void +}> = ({ onPress = goBack, show = true, showCloseIcon = false }) => { const isFirstRender = useFirstMountState() const opacity = useRef(new Animated.Value(show ? 1 : 0)).current useEffect(() => { @@ -39,7 +39,11 @@ export const BackButton: React.FC<{ show?: boolean; showCloseIcon?: boolean; onP onPress={onPress} style={{ width: "100%", height: "100%", alignItems: "center", justifyContent: "center" }} > - {showCloseIcon ? : } + {showCloseIcon ? ( + + ) : ( + + )} ) diff --git a/src/lib/navigation/ModalStack.tsx b/src/lib/navigation/ModalStack.tsx index 7f53ab12742..6d5b68a68f2 100644 --- a/src/lib/navigation/ModalStack.tsx +++ b/src/lib/navigation/ModalStack.tsx @@ -18,7 +18,10 @@ export const ModalStack: React.FC = ({ children }) => { const initialState = useReloadedDevNavigationState("main_modal_stack", __unsafe_mainModalStackRef) return ( - + {() => children} @@ -26,9 +29,9 @@ export const ModalStack: React.FC = ({ children }) => { ) } -const ModalNavStack: React.FC<{ route: Route<"", { rootModuleName: AppModule; rootModuleProps?: object }> }> = ({ - route, -}) => { +const ModalNavStack: React.FC<{ + route: Route<"", { rootModuleName: AppModule; rootModuleProps?: object }> +}> = ({ route }) => { return ( }> = ({ route }) = const [legacy_shouldHideBackButton, updateShouldHideBackButton] = useState(false) const isRootScreen = useNavigationState((state) => state.routes[0].key === route.key) - const showBackButton = !isRootScreen && !module.options.hidesBackButton && !legacy_shouldHideBackButton + const showBackButton = + !isRootScreen && !module.options.hidesBackButton && !legacy_shouldHideBackButton const isPresentedModally = (route.params.props as any)?.isPresentedModally @@ -38,7 +39,9 @@ const ScreenWrapper: React.FC<{ route: Route<"", ScreenProps> }> = ({ route }) = return ( - + }> = ({ route }) = ) } -const ScreenPadding: React.FC<{ fullBleed: boolean; isPresentedModally: boolean; isVisible: boolean }> = ({ - fullBleed, - children, -}) => { +const ScreenPadding: React.FC<{ + fullBleed: boolean + isPresentedModally: boolean + isVisible: boolean +}> = ({ fullBleed, children }) => { const topInset = useScreenDimensions().safeAreaInsets.top - return {children} + return ( + + {children} + + ) } /** * NavStack is a native navigation stack. Each tab in the main view has its own NavStack. Each modal that * is presented (excluding FancyModal) also has its own NavStack. */ -export const NavStack: React.FC<{ id: string; rootModuleName: AppModule; rootModuleProps?: any }> = ({ - id, - rootModuleName, - rootModuleProps, -}) => { +export const NavStack: React.FC<{ + id: string + rootModuleName: AppModule + rootModuleProps?: any +}> = ({ id, rootModuleName, rootModuleProps }) => { const initialParams: ScreenProps = { moduleName: rootModuleName, props: rootModuleProps, diff --git a/src/lib/navigation/RouteMatcher.tests.ts b/src/lib/navigation/RouteMatcher.tests.ts index 6ea1eb0c842..920387b5d04 100644 --- a/src/lib/navigation/RouteMatcher.tests.ts +++ b/src/lib/navigation/RouteMatcher.tests.ts @@ -65,7 +65,9 @@ describe(RouteMatcher, () => { expect(new RouteMatcher("/home", "Home").match(["home"])).toEqual({}) expect(new RouteMatcher("/:id", "Home").match(["david"])).toEqual({ id: "david" }) expect(new RouteMatcher("/:id/home", "Home").match(["david", "home"])).toEqual({ id: "david" }) - expect(new RouteMatcher("/home/:id", "Home").match(["home", "stephen"])).toEqual({ id: "stephen" }) + expect(new RouteMatcher("/home/:id", "Home").match(["home", "stephen"])).toEqual({ + id: "stephen", + }) expect( new RouteMatcher("/home/:id/thing/:slug/other_thing/:slug2", "Home").match([ "home", diff --git a/src/lib/navigation/RouteMatcher.ts b/src/lib/navigation/RouteMatcher.ts index 318ee8675d8..627f32a9c43 100644 --- a/src/lib/navigation/RouteMatcher.ts +++ b/src/lib/navigation/RouteMatcher.ts @@ -1,10 +1,17 @@ import { AppModule } from "lib/AppRegistry" -type RoutePart = { type: "match"; value: string } | { type: "variable"; name: string } | { type: "wildcard" } +type RoutePart = + | { type: "match"; value: string } + | { type: "variable"; name: string } + | { type: "wildcard" } export class RouteMatcher { private parts: ReadonlyArray - constructor(public route: string, public module: AppModule, private paramsMapper?: (val: any) => object) { + constructor( + public route: string, + public module: AppModule, + private paramsMapper?: (val: any) => object + ) { if (!route.match(/^(\/\*?|(\/:?[\w-]+)+(\/\*)?)$/)) { throw new Error(`Invalid route format '${route}'. diff --git a/src/lib/navigation/navigate.tests.tsx b/src/lib/navigation/navigate.tests.tsx index 82a82c2740d..8b36b223685 100644 --- a/src/lib/navigation/navigate.tests.tsx +++ b/src/lib/navigation/navigate.tests.tsx @@ -21,7 +21,8 @@ describe(navigate, () => { it("like artwork", () => { navigate("/artwork/josef-albers-homage-to-the-square") expect(LegacyNativeModules.ARScreenPresenterModule.pushView).toHaveBeenCalled() - expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)) + .toMatchInlineSnapshot(` Array [ "home", Object { @@ -38,7 +39,8 @@ describe(navigate, () => { it("like artist", () => { navigate("/artist/banksy") expect(LegacyNativeModules.ARScreenPresenterModule.pushView).toHaveBeenCalled() - expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)) + .toMatchInlineSnapshot(` Array [ "home", Object { @@ -56,7 +58,8 @@ describe(navigate, () => { it("like vanity urls", () => { navigate("/artsy-vanguard-2019") expect(LegacyNativeModules.ARScreenPresenterModule.pushView).toHaveBeenCalled() - expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)) + .toMatchInlineSnapshot(` Array [ "home", Object { @@ -85,7 +88,8 @@ describe(navigate, () => { }, }) expect(LegacyNativeModules.ARScreenPresenterModule.pushView).toHaveBeenCalled() - expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)) + .toMatchInlineSnapshot(` Array [ "home", Object { @@ -105,7 +109,8 @@ describe(navigate, () => { describe("presents modals", () => { it("when the screen requires it", () => { navigate("https://live.artsy.net/blah") - expect(args(LegacyNativeModules.ARScreenPresenterModule.presentModal as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.presentModal as any)) + .toMatchInlineSnapshot(` Array [ Object { "alwaysPresentModally": true, @@ -131,13 +136,17 @@ describe(navigate, () => { it("switches tab and pops the view stack when routing to a root tab view", async () => { await navigate("/search") expect(GlobalStore.actions.bottomTabs.switchTab).toHaveBeenCalledWith("search") - expect(LegacyNativeModules.ARScreenPresenterModule.popToRootAndScrollToTop).toHaveBeenCalledWith("search") + expect( + LegacyNativeModules.ARScreenPresenterModule.popToRootAndScrollToTop + ).toHaveBeenCalledWith("search") }) it("passes tab props when switching", async () => { await navigate("/search?query=banksy") expect(GlobalStore.actions.bottomTabs.switchTab).toHaveBeenCalledWith("search") - expect(LegacyNativeModules.ARScreenPresenterModule.popToRootAndScrollToTop).toHaveBeenCalledWith("search") + expect( + LegacyNativeModules.ARScreenPresenterModule.popToRootAndScrollToTop + ).toHaveBeenCalledWith("search") expect(GlobalStore.actions.bottomTabs.setTabProps).toHaveBeenCalledWith({ tab: "search", props: { query: "banksy" }, @@ -148,7 +157,8 @@ describe(navigate, () => { await navigate("/conversation/234") expect(GlobalStore.actions.bottomTabs.switchTab).toHaveBeenCalledWith("inbox") await flushPromiseQueue() - expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)) + .toMatchInlineSnapshot(` Array [ "inbox", Object { @@ -174,7 +184,8 @@ describe(navigate, () => { await flushPromiseQueue() expect(GlobalStore.actions.bottomTabs.switchTab).toHaveBeenCalledWith("profile") - expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)).toMatchInlineSnapshot(` + expect(args(LegacyNativeModules.ARScreenPresenterModule.pushView as any)) + .toMatchInlineSnapshot(` Array [ "profile", Object { diff --git a/src/lib/navigation/navigate.ts b/src/lib/navigation/navigate.ts index 58d8908d39c..d8716c982b9 100644 --- a/src/lib/navigation/navigate.ts +++ b/src/lib/navigation/navigate.ts @@ -73,7 +73,9 @@ export async function navigate(url: string, options: NavigateOptions = {}) { } else if (module.options.isRootViewForTabName) { // this view is one of our root tab views, e.g. home, search, etc. // switch to the tab, pop the stack, and scroll to the top. - await LegacyNativeModules.ARScreenPresenterModule.popToRootAndScrollToTop(module.options.isRootViewForTabName) + await LegacyNativeModules.ARScreenPresenterModule.popToRootAndScrollToTop( + module.options.isRootViewForTabName + ) switchTab(module.options.isRootViewForTabName, screenDescriptor.props) } else { const onlyShowInTabName = module.options.onlyShowInTabName || showInTabName @@ -83,7 +85,10 @@ export async function navigate(url: string, options: NavigateOptions = {}) { // we will need to delay the navigation action until we change tabs const waitForTabsToChange = !!onlyShowInTabName && onlyShowInTabName !== selectedTab const pushView = () => { - LegacyNativeModules.ARScreenPresenterModule.pushView(onlyShowInTabName ?? selectedTab, screenDescriptor) + LegacyNativeModules.ARScreenPresenterModule.pushView( + onlyShowInTabName ?? selectedTab, + screenDescriptor + ) } // If the screen should be on a tab, then switch to this tab first diff --git a/src/lib/navigation/routes.tests.tsx b/src/lib/navigation/routes.tests.tsx index 93b061f20b8..b55d5a3ce13 100644 --- a/src/lib/navigation/routes.tests.tsx +++ b/src/lib/navigation/routes.tests.tsx @@ -93,8 +93,11 @@ describe("artsy.net routes", () => { "type": "match", } `) - expect(matchRoute("artist/josef-albers?utm_medium=social&utm_source=instagram-story&utm_campaign=dp.")) - .toMatchInlineSnapshot(` + expect( + matchRoute( + "artist/josef-albers?utm_medium=social&utm_source=instagram-story&utm_campaign=dp." + ) + ).toMatchInlineSnapshot(` Object { "module": "Artist", "params": Object { @@ -161,8 +164,11 @@ describe("artsy.net routes", () => { "type": "match", } `) - expect(matchRoute(encodeURIComponent(encodeURIComponent("https://www.artsy.net/artwork/more%26more")))) - .toMatchInlineSnapshot(` + expect( + matchRoute( + encodeURIComponent(encodeURIComponent("https://www.artsy.net/artwork/more%26more")) + ) + ).toMatchInlineSnapshot(` Object { "module": "Artwork", "params": Object { @@ -172,7 +178,9 @@ describe("artsy.net routes", () => { } `) expect( - matchRoute("/artwork/yayoi-kusama-red-pumpkin?utm_medium=social&utm_source=instagram-story&utm_campaign=dp.") + matchRoute( + "/artwork/yayoi-kusama-red-pumpkin?utm_medium=social&utm_source=instagram-story&utm_campaign=dp." + ) ).toMatchInlineSnapshot(` Object { "module": "Artwork", @@ -320,7 +328,8 @@ describe("artsy.net routes", () => { }) it("routes to AuctionBidArtwork", () => { - expect(matchRoute("/auction/special-auction/bid/josef-albers-homage-to-the-square")).toMatchInlineSnapshot(` + expect(matchRoute("/auction/special-auction/bid/josef-albers-homage-to-the-square")) + .toMatchInlineSnapshot(` Object { "module": "AuctionBidArtwork", "params": Object { @@ -330,7 +339,8 @@ describe("artsy.net routes", () => { "type": "match", } `) - expect(matchRoute("/auction/other-auction/bid/yayoi-kusama-red-pumpkin")).toMatchInlineSnapshot(` + expect(matchRoute("/auction/other-auction/bid/yayoi-kusama-red-pumpkin")) + .toMatchInlineSnapshot(` Object { "module": "AuctionBidArtwork", "params": Object { @@ -480,7 +490,8 @@ describe("artsy.net routes", () => { }) it("routes to ViewingRoomArtwork", () => { - expect(matchRoute("/viewing-room/red/josef-albers-homage-to-the-square")).toMatchInlineSnapshot(` + expect(matchRoute("/viewing-room/red/josef-albers-homage-to-the-square")) + .toMatchInlineSnapshot(` Object { "module": "ViewingRoomArtwork", "params": Object { @@ -1267,9 +1278,12 @@ describe("other domains", () => { describe(replaceParams, () => { it("replaces the params in a url with params from an object", () => { expect(replaceParams("/artist/:id", { id: "banksy" })).toBe("/artist/banksy") - expect(replaceParams("/bid/:saleID/:artworkID", { saleID: "christies", artworkID: "keith-haring-dog" })).toBe( - "/bid/christies/keith-haring-dog" - ) + expect( + replaceParams("/bid/:saleID/:artworkID", { + saleID: "christies", + artworkID: "keith-haring-dog", + }) + ).toBe("/bid/christies/keith-haring-dog") expect(replaceParams("/artist/:artistID/auction-results", { artistID: "josef-albers" })).toBe( "/artist/josef-albers/auction-results" ) diff --git a/src/lib/navigation/routes.tsx b/src/lib/navigation/routes.tsx index 2a3fc8d4bb3..c3ca7b1f00a 100644 --- a/src/lib/navigation/routes.tsx +++ b/src/lib/navigation/routes.tsx @@ -141,7 +141,9 @@ function getDomainMap(): Record { unsafe_getFeatureFlag("AROptionsNewSalePage") ? new RouteMatcher("/auction/:saleID", "Auction2") : new RouteMatcher("/auction/:id", "Auction"), - unsafe_getFeatureFlag("AROptionsNewSalePage") ? new RouteMatcher("/auction/:saleID/info", "AuctionInfo") : null, + unsafe_getFeatureFlag("AROptionsNewSalePage") + ? new RouteMatcher("/auction/:saleID/info", "AuctionInfo") + : null, new RouteMatcher("/auction-faq", "AuctionFAQ"), new RouteMatcher("/auction/:saleID/bid/:artworkID", "AuctionBidArtwork"), new RouteMatcher("/gene/:geneID", "Gene"), @@ -151,7 +153,10 @@ function getDomainMap(): Record { new RouteMatcher("/inquiry/:artworkID", "Inquiry"), new RouteMatcher("/viewing-rooms", "ViewingRooms"), - new RouteMatcher("/auction-results-for-artists-you-follow", "AuctionResultsForArtistsYouFollow"), + new RouteMatcher( + "/auction-results-for-artists-you-follow", + "AuctionResultsForArtistsYouFollow" + ), new RouteMatcher("/viewing-room/:viewing_room_id", "ViewingRoom"), new RouteMatcher("/viewing-room/:viewing_room_id/artworks", "ViewingRoomArtworks"), new RouteMatcher("/viewing-room/:viewing_room_id/:artwork_id", "ViewingRoomArtwork"), @@ -186,12 +191,18 @@ function getDomainMap(): Record { new RouteMatcher("/my-collection", "MyCollection"), new RouteMatcher("/my-collection/artwork/:artworkSlug", "MyCollectionArtwork"), - new RouteMatcher("/my-collection/artwork-details/:artworkSlug", "MyCollectionArtworkFullDetails"), + new RouteMatcher( + "/my-collection/artwork-details/:artworkSlug", + "MyCollectionArtworkFullDetails" + ), new RouteMatcher("/my-collection/artworks/new", "AddOrEditMyCollectionArtwork"), new RouteMatcher("/my-collection/artworks/:artworkID/edit", "AddOrEditMyCollectionArtwork"), // TODO: Follow-up about below route names - new RouteMatcher("/collections/my-collection/artworks/new/submissions/new", "ConsignmentsSubmissionForm"), + new RouteMatcher( + "/collections/my-collection/artworks/new/submissions/new", + "ConsignmentsSubmissionForm" + ), new RouteMatcher("/consign/submission", "ConsignmentsSubmissionForm"), new RouteMatcher("/collections/my-collection/marketing-landing", "SalesNotRootTabView"), @@ -233,7 +244,10 @@ function getDomainMap(): Record { new RouteMatcher("/my-profile/saved-search-alerts", "SavedSearchAlertsList"), new RouteMatcher("/my-profile/saved-search-alerts/:savedSearchAlertId", "EditSavedSearchAlert"), unsafe_getFeatureFlag("AROptionsUseReactNativeWebView") - ? webViewRoute("/orders/:orderID", { mimicBrowserBackButton: true, useRightCloseButton: true }) + ? webViewRoute("/orders/:orderID", { + mimicBrowserBackButton: true, + useRightCloseButton: true, + }) : new RouteMatcher("/orders/:orderID", "Checkout"), __DEV__ && new RouteMatcher("/storybook", "Storybook"), diff --git a/src/lib/navigation/useReloadedDevNavigationState.ts b/src/lib/navigation/useReloadedDevNavigationState.ts index 0acee0b3e39..2a41f5f9454 100644 --- a/src/lib/navigation/useReloadedDevNavigationState.ts +++ b/src/lib/navigation/useReloadedDevNavigationState.ts @@ -24,7 +24,9 @@ const currentCache: NavStateCache = { // On dev mode, if the app restarted because of a bundle reload/fast refresh, // We want to rehydrate the navigation state -export async function loadDevNavigationStateCache(switchTabAction: (tabName: BottomTabType) => void) { +export async function loadDevNavigationStateCache( + switchTabAction: (tabName: BottomTabType) => void +) { if (!__DEV__) { return } diff --git a/src/lib/relay/RelayCache.tests.tsx b/src/lib/relay/RelayCache.tests.tsx index d056b5d134d..e6edd02dd9b 100644 --- a/src/lib/relay/RelayCache.tests.tsx +++ b/src/lib/relay/RelayCache.tests.tsx @@ -5,7 +5,9 @@ describe(requestFingerprint, () => { it("makes a fingerprint of a graphql request with a stable key ordering", () => { const fingerprintA = requestFingerprint("myQueryID", { a: "A", b: "B", c: "C" }) const fingerprintB = requestFingerprint("myQueryID", { b: "B", c: "C", a: "A" }) - expect(fingerprintA).toMatchInlineSnapshot(`"{\\"myQueryID\\":{\\"a\\":\\"A\\",\\"b\\":\\"B\\",\\"c\\":\\"C\\"}}"`) + expect(fingerprintA).toMatchInlineSnapshot( + `"{\\"myQueryID\\":{\\"a\\":\\"A\\",\\"b\\":\\"B\\",\\"c\\":\\"C\\"}}"` + ) expect(fingerprintA).toEqual(fingerprintB) }) it("works with nested objects and arrays", () => { diff --git a/src/lib/relay/RelayCache.ts b/src/lib/relay/RelayCache.ts index de6fef31104..1a8e4086738 100644 --- a/src/lib/relay/RelayCache.ts +++ b/src/lib/relay/RelayCache.ts @@ -29,7 +29,12 @@ interface CacheRecord { expires: number } -export async function set(queryID: string, variables: object, response: string | null, ttlSeconds: number = 0) { +export async function set( + queryID: string, + variables: object, + response: string | null, + ttlSeconds: number = 0 +) { if (ttlSeconds === 0) { // default should be one day according to objc code ttlSeconds = 60 * 60 * 24 diff --git a/src/lib/relay/createEnvironment.ts b/src/lib/relay/createEnvironment.ts index c6761b2878d..998d4e90dee 100644 --- a/src/lib/relay/createEnvironment.ts +++ b/src/lib/relay/createEnvironment.ts @@ -1,4 +1,7 @@ -import { errorMiddleware as relayErrorMiddleware, RelayNetworkLayer } from "react-relay-network-modern/node8" +import { + errorMiddleware as relayErrorMiddleware, + RelayNetworkLayer, +} from "react-relay-network-modern/node8" import { Environment, RecordSource, Store } from "relay-runtime" import { cacheMiddleware } from "./middlewares/cacheMiddleware" diff --git a/src/lib/relay/middlewares/cacheMiddleware.ts b/src/lib/relay/middlewares/cacheMiddleware.ts index e683ee2836c..6d1c06aad80 100644 --- a/src/lib/relay/middlewares/cacheMiddleware.ts +++ b/src/lib/relay/middlewares/cacheMiddleware.ts @@ -31,7 +31,12 @@ export const cacheMiddleware = () => { if (isQuery) { // Don't cache responses with errors in them (GraphQL responses are always 200, even if they contain errors). if ((response.json as any).errors === undefined) { - cache.set(queryID!, req.variables, JSON.stringify(response.json), req.cacheConfig.emissionCacheTTLSeconds) + cache.set( + queryID!, + req.variables, + JSON.stringify(response.json), + req.cacheConfig.emissionCacheTTLSeconds + ) } else { clearCache() return response diff --git a/src/lib/relay/middlewares/checkAuthenticationMiddleware.tests.ts b/src/lib/relay/middlewares/checkAuthenticationMiddleware.tests.ts index e5d6f7ef1e8..59220d50ab8 100644 --- a/src/lib/relay/middlewares/checkAuthenticationMiddleware.tests.ts +++ b/src/lib/relay/middlewares/checkAuthenticationMiddleware.tests.ts @@ -1,5 +1,9 @@ import { __globalStoreTestUtils__ } from "lib/store/GlobalStore" -import { GraphQLResponseErrors, MiddlewareNextFn, RelayNetworkLayerResponse } from "react-relay-network-modern/node8" +import { + GraphQLResponseErrors, + MiddlewareNextFn, + RelayNetworkLayerResponse, +} from "react-relay-network-modern/node8" import { checkAuthenticationMiddleware } from "./checkAuthenticationMiddleware" import { GraphQLRequest } from "./types" @@ -20,7 +24,9 @@ describe(checkAuthenticationMiddleware, () => { } it("calls signOut if there are errors", async () => { - const errors: GraphQLResponseErrors = [{ message: "The access token is invalid or has expired." }] + const errors: GraphQLResponseErrors = [ + { message: "The access token is invalid or has expired." }, + ] // @ts-ignore const relayResponse: RelayNetworkLayerResponse = { errors } @@ -29,8 +35,12 @@ describe(checkAuthenticationMiddleware, () => { expect(fetchMock).toHaveBeenCalledTimes(0) await middleware(next)(request) expect(fetchMock).toHaveBeenCalledTimes(1) - expect(__globalStoreTestUtils__?.dispatchedActions.map((x) => x.type)).toContain("@thunk.auth.signOut") - expect(__globalStoreTestUtils__?.dispatchedActions.map((x) => x.type)).toContain("@thunkOn.resetAfterSignOut") + expect(__globalStoreTestUtils__?.dispatchedActions.map((x) => x.type)).toContain( + "@thunk.auth.signOut" + ) + expect(__globalStoreTestUtils__?.dispatchedActions.map((x) => x.type)).toContain( + "@thunkOn.resetAfterSignOut" + ) }) it("passes through if there is no errors", async () => { diff --git a/src/lib/relay/middlewares/errorMiddleware.ts b/src/lib/relay/middlewares/errorMiddleware.ts index 5734f39d6cb..608b04d4b4e 100644 --- a/src/lib/relay/middlewares/errorMiddleware.ts +++ b/src/lib/relay/middlewares/errorMiddleware.ts @@ -35,7 +35,11 @@ const throwError = (req: GraphQLRequest, res: RelayNetworkLayerResponse) => { throw createRequestError(req, res) } -const trackError = (queryName: string, queryKind: string, handler: "optionalField" | "principalField" | "default") => { +const trackError = ( + queryName: string, + queryKind: string, + handler: "optionalField" | "principalField" | "default" +) => { volleyClient.send({ type: "increment", name: "graphql-request-with-errors", @@ -55,8 +59,9 @@ export const errorMiddleware = () => { return res } - // @ts-ignore RELAY 12 MIGRATION - const allErrorsAreOptional = resJson.extensions?.optionalFields?.length === resJson.errors?.length + const allErrorsAreOptional = + // @ts-ignore RELAY 12 MIGRATION + resJson.extensions?.optionalFields?.length === resJson.errors?.length if (allErrorsAreOptional) { trackError(req.operation.name, req.operation.kind, "optionalField") @@ -77,7 +82,10 @@ export const errorMiddleware = () => { // This represents whether or not the query experienced an error and that error was thrown while resolving // a field marked with the @principalField directive, or any sub-selection of such a field. // @ts-ignore RELAY 12 MIGRATION - const principalFieldWasInvolvedInError = isErrorStatus(resJson.extensions?.principalField?.httpStatusCode) + const principalFieldWasInvolvedInError = isErrorStatus( + // @ts-ignore RELAY 12 MIGRATION + resJson.extensions?.principalField?.httpStatusCode + ) if (principalFieldWasInvolvedInError) { trackError(req.operation.name, req.operation.kind, "principalField") diff --git a/src/lib/relay/middlewares/rateLimitMiddleware.tests.ts b/src/lib/relay/middlewares/rateLimitMiddleware.tests.ts index 2da769460fb..1e7d2c3a3ce 100644 --- a/src/lib/relay/middlewares/rateLimitMiddleware.tests.ts +++ b/src/lib/relay/middlewares/rateLimitMiddleware.tests.ts @@ -1,4 +1,8 @@ -import { MiddlewareNextFn, RelayNetworkLayerRequest, RelayNetworkLayerResponse } from "react-relay-network-modern/node8" +import { + MiddlewareNextFn, + RelayNetworkLayerRequest, + RelayNetworkLayerResponse, +} from "react-relay-network-modern/node8" import { rateLimitMiddleware } from "./rateLimitMiddleware" describe("rateLimitMiddleware", () => { diff --git a/src/lib/relay/middlewares/rateLimitMiddleware.ts b/src/lib/relay/middlewares/rateLimitMiddleware.ts index 9a6fb9ff3e3..130087059a5 100644 --- a/src/lib/relay/middlewares/rateLimitMiddleware.ts +++ b/src/lib/relay/middlewares/rateLimitMiddleware.ts @@ -8,7 +8,11 @@ interface RateLimitMiddlewareOpts { } export const rateLimitMiddleware = ( - { limit, interval, logger = console.log.bind(console, "[RELAY-NETWORK]") }: RateLimitMiddlewareOpts = { + { + limit, + interval, + logger = console.log.bind(console, "[RELAY-NETWORK]"), + }: RateLimitMiddlewareOpts = { limit: 50, interval: 1000, } diff --git a/src/lib/relay/middlewares/simpleLoggerMiddleware.ts b/src/lib/relay/middlewares/simpleLoggerMiddleware.ts index 533c8385131..65370699637 100644 --- a/src/lib/relay/middlewares/simpleLoggerMiddleware.ts +++ b/src/lib/relay/middlewares/simpleLoggerMiddleware.ts @@ -20,7 +20,11 @@ export function simpleLoggerMiddleware(): Middleware { "with response", response.data, ...(response.errors?.length - ? ["and errors\n\n" + response.errors.map((err, i) => ` ${i + 1}. ${err.message}`).join("\n"), "\n"] + ? [ + "and errors\n\n" + + response.errors.map((err, i) => ` ${i + 1}. ${err.message}`).join("\n"), + "\n", + ] : []) ) } diff --git a/src/lib/store/AuthModel.tests.ts b/src/lib/store/AuthModel.tests.ts index 758524048e8..b014fcae7d6 100644 --- a/src/lib/store/AuthModel.tests.ts +++ b/src/lib/store/AuthModel.tests.ts @@ -144,7 +144,9 @@ describe("AuthModel", () => { expect(result).toBe(true) expect(mockFetch).toHaveBeenCalledTimes(2) - expect(mockFetch.mock.calls[0][0]).toMatchInlineSnapshot(`"https://stagingapi.artsy.net/oauth2/access_token"`) + expect(mockFetch.mock.calls[0][0]).toMatchInlineSnapshot( + `"https://stagingapi.artsy.net/oauth2/access_token"` + ) expect(JSON.parse(mockFetch.mock.calls[0][1].body)).toMatchInlineSnapshot(` Object { "client_id": "artsy_api_client_key", @@ -175,8 +177,12 @@ describe("AuthModel", () => { password: "hunter2", }) - expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe("my-access-token") - expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessTokenExpiresIn).toBe("a billion years") + expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe( + "my-access-token" + ) + expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessTokenExpiresIn).toBe( + "a billion years" + ) expect(__globalStoreTestUtils__?.getCurrentState().auth.userID).toBe("my-user-id") }) @@ -184,7 +190,11 @@ describe("AuthModel", () => { mockFetchJsonOnce({ access_token: "my-access-token", expires_in: "a billion years" }, 201) mockFetchJsonOnce({ id: "my-user-id" }) - await GlobalStore.actions.auth.signIn({ oauthProvider: "email", email: "user@example.com", password: "hunter2" }) + await GlobalStore.actions.auth.signIn({ + oauthProvider: "email", + email: "user@example.com", + password: "hunter2", + }) expect(mockPostEventToProviders).toHaveBeenCalledTimes(1) expect(mockPostEventToProviders.mock.calls[0]).toMatchInlineSnapshot(` @@ -291,8 +301,12 @@ describe("AuthModel", () => { expect(result.success).toBe(true) expect(__globalStoreTestUtils__?.getCurrentState().auth.onboardingState).toBe("incomplete") - expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe("my-access-token") - expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessTokenExpiresIn).toBe("a billion years") + expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe( + "my-access-token" + ) + expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessTokenExpiresIn).toBe( + "a billion years" + ) expect(__globalStoreTestUtils__?.getCurrentState().auth.userID).toBe("my-user-id") }) @@ -318,14 +332,18 @@ describe("AuthModel", () => { await GlobalStore.actions.auth.getXAppToken() mockFetch.mockClear() ;(LoginManager.logInWithPermissions as jest.Mock).mockReturnValue({ isCancelled: false }) - ;(AccessToken.getCurrentAccessToken as jest.Mock).mockReturnValue({ accessToken: "facebook-token" }) + ;(AccessToken.getCurrentAccessToken as jest.Mock).mockReturnValue({ + accessToken: "facebook-token", + }) ;(GraphRequest as jest.Mock).mockImplementation((_route, _config, callback) => { callback(undefined, { email: "emailFromFacebook@email.com", name: "name from facebook" }) }) }) it("throws an error when email permission was denied", async () => { - ;(LoginManager.logInWithPermissions as jest.Mock).mockReturnValue({ declinedPermissions: ["email"] }) + ;(LoginManager.logInWithPermissions as jest.Mock).mockReturnValue({ + declinedPermissions: ["email"], + }) const result = await GlobalStore.actions.auth .authFacebook({ signInOrUp: "signUp", agreedToReceiveEmails: true }) @@ -352,7 +370,10 @@ describe("AuthModel", () => { it("fetches access token from facebook", async () => { GlobalStore.actions.auth.signUp = jest.fn(() => ({ success: true })) as any - await GlobalStore.actions.auth.authFacebook({ signInOrUp: "signUp", agreedToReceiveEmails: true }) + await GlobalStore.actions.auth.authFacebook({ + signInOrUp: "signUp", + agreedToReceiveEmails: true, + }) expect(AccessToken.getCurrentAccessToken).toHaveBeenCalled() }) @@ -372,7 +393,10 @@ describe("AuthModel", () => { it("fetches profile info from facebook and signs up", async () => { GlobalStore.actions.auth.signUp = jest.fn(() => ({ success: true })) as any - await GlobalStore.actions.auth.authFacebook({ signInOrUp: "signUp", agreedToReceiveEmails: true }) + await GlobalStore.actions.auth.authFacebook({ + signInOrUp: "signUp", + agreedToReceiveEmails: true, + }) expect(GlobalStore.actions.auth.signUp).toHaveBeenCalledWith({ email: "emailFromFacebook@email.com", @@ -384,7 +408,10 @@ describe("AuthModel", () => { }) it("throws an error if sign up fails", async () => { - GlobalStore.actions.auth.signUp = jest.fn(() => ({ success: false, message: "Could not sign up" })) as any + GlobalStore.actions.auth.signUp = jest.fn(() => ({ + success: false, + message: "Could not sign up", + })) as any const result = await GlobalStore.actions.auth .authFacebook({ signInOrUp: "signUp", agreedToReceiveEmails: true }) @@ -429,7 +456,9 @@ describe("AuthModel", () => { it("throws an error if getting X-ACCESS-TOKEN fails", async () => { mockFetchJsonOnce({ error_description: "getting X-ACCESS-TOKEN error" }) - const result = await GlobalStore.actions.auth.authFacebook({ signInOrUp: "signIn" }).catch((e) => e) + const result = await GlobalStore.actions.auth + .authFacebook({ signInOrUp: "signIn" }) + .catch((e) => e) expect(result).toBe("Login attempt failed") }) @@ -463,7 +492,10 @@ describe("AuthModel", () => { it("fetches profile info from google and signs up", async () => { GlobalStore.actions.auth.signUp = jest.fn(() => ({ success: true })) as any - await GlobalStore.actions.auth.authGoogle({ signInOrUp: "signUp", agreedToReceiveEmails: false }) + await GlobalStore.actions.auth.authGoogle({ + signInOrUp: "signUp", + agreedToReceiveEmails: false, + }) expect(GlobalStore.actions.auth.signUp).toHaveBeenCalledWith({ email: "googleEmail@gmail.com", @@ -475,7 +507,10 @@ describe("AuthModel", () => { }) it("throws an error if sign up fails", async () => { - GlobalStore.actions.auth.signUp = jest.fn(() => ({ success: false, message: "Could not sign up" })) as any + GlobalStore.actions.auth.signUp = jest.fn(() => ({ + success: false, + message: "Could not sign up", + })) as any const result = await GlobalStore.actions.auth .authGoogle({ signInOrUp: "signUp", agreedToReceiveEmails: true }) @@ -520,7 +555,9 @@ describe("AuthModel", () => { it("throws an error if getting X-ACCESS-TOKEN fails", async () => { mockFetchJsonOnce({ error_description: "getting X-ACCESS-TOKEN error" }) - const result = await GlobalStore.actions.auth.authGoogle({ signInOrUp: "signIn" }).catch((e) => e) + const result = await GlobalStore.actions.auth + .authGoogle({ signInOrUp: "signIn" }) + .catch((e) => e) expect(result).toBe("Login attempt failed") }) @@ -534,7 +571,10 @@ describe("AuthModel", () => { }) await GlobalStore.actions.auth.getXAppToken() mockFetch.mockClear() - ;(appleAuth.performRequest as jest.Mock).mockReturnValue({ identityToken: "apple-id-token", user: "appleUID" }) + ;(appleAuth.performRequest as jest.Mock).mockReturnValue({ + identityToken: "apple-id-token", + user: "appleUID", + }) }) it("fetches profile info from apple and signs up", async () => { @@ -640,7 +680,9 @@ describe("AuthModel", () => { }) it("clears user access token", async () => { - expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe("user-access-token") + expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe( + "user-access-token" + ) await GlobalStore.actions.auth.signOut() expect(__globalStoreTestUtils__?.getCurrentState().auth.userAccessToken).toBe(null) }) diff --git a/src/lib/store/AuthModel.ts b/src/lib/store/AuthModel.ts index bea77b9e3b8..114155ce27c 100644 --- a/src/lib/store/AuthModel.ts +++ b/src/lib/store/AuthModel.ts @@ -2,17 +2,35 @@ import { ActionType, AuthService, CreatedAccount } from "@artsy/cohesion" import { appleAuth } from "@invertase/react-native-apple-authentication" import CookieManager from "@react-native-cookies/cookies" import { GoogleSignin } from "@react-native-google-signin/google-signin" -import { action, Action, Computed, computed, StateMapper, thunk, Thunk, thunkOn, ThunkOn } from "easy-peasy" +import { + action, + Action, + Computed, + computed, + StateMapper, + thunk, + Thunk, + thunkOn, + ThunkOn, +} from "easy-peasy" import * as RelayCache from "lib/relay/RelayCache" import { isArtsyEmail } from "lib/utils/general" -import { getNotificationPermissionsStatus, PushAuthorizationStatus } from "lib/utils/PushNotification" +import { + getNotificationPermissionsStatus, + PushAuthorizationStatus, +} from "lib/utils/PushNotification" import { postEventToProviders } from "lib/utils/track/providers" import { SegmentTrackingProvider } from "lib/utils/track/SegmentTrackingProvider" import { capitalize } from "lodash" import { stringify } from "qs" import { Alert, Linking, Platform } from "react-native" import Config from "react-native-config" -import { AccessToken, GraphRequest, GraphRequestManager, LoginManager } from "react-native-fbsdk-next" +import { + AccessToken, + GraphRequest, + GraphRequestManager, + LoginManager, +} from "react-native-fbsdk-next" import Keychain from "react-native-keychain" import { LegacyNativeModules } from "../NativeModules/LegacyNativeModules" import { getCurrentEmissionState } from "./GlobalStore" @@ -20,7 +38,11 @@ import type { GlobalStoreModel } from "./GlobalStoreModel" type BasicHttpMethod = "GET" | "PUT" | "POST" | "DELETE" -const afterSocialAuthLogin = (res: any, reject: (reason?: any) => void, provider: "facebook" | "apple" | "google") => { +const afterSocialAuthLogin = ( + res: any, + reject: (reason?: any) => void, + provider: "facebook" | "apple" | "google" +) => { const providerName = capitalize(provider) if (res.error_description) { if (res.error_description.includes("no account linked to oauth token")) { @@ -237,7 +259,8 @@ export const getAuthModel = (): AuthModel => ({ oauth_provider: oauthProvider, password: oauthProvider === "email" ? args.password : undefined, - oauth_token: oauthProvider === "facebook" || oauthProvider === "google" ? args.accessToken : undefined, + oauth_token: + oauthProvider === "facebook" || oauthProvider === "google" ? args.accessToken : undefined, apple_uid: oauthProvider === "apple" ? args.appleUID : undefined, id_token: oauthProvider === "apple" ? args.idToken : undefined, grant_type: grantTypeMap[oauthProvider], @@ -314,7 +337,8 @@ export const getAuthModel = (): AuthModel => ({ name, password: oauthProvider === "email" ? args.password : undefined, - oauth_token: oauthProvider === "facebook" || oauthProvider === "google" ? args.accessToken : undefined, + oauth_token: + oauthProvider === "facebook" || oauthProvider === "google" ? args.accessToken : undefined, apple_uid: oauthProvider === "apple" ? args.appleUID : undefined, id_token: oauthProvider === "apple" ? args.idToken : undefined, @@ -381,7 +405,10 @@ export const getAuthModel = (): AuthModel => ({ }), authFacebook: thunk(async (actions, options) => { return await new Promise(async (resolve, reject) => { - const { declinedPermissions, isCancelled } = await LoginManager.logInWithPermissions(["public_profile", "email"]) + const { declinedPermissions, isCancelled } = await LoginManager.logInWithPermissions([ + "public_profile", + "email", + ]) if (declinedPermissions?.includes("email")) { reject("Please allow the use of email to continue.") } @@ -620,7 +647,9 @@ export const getAuthModel = (): AuthModel => ({ } await Promise.all([ - Platform.OS === "ios" ? await LegacyNativeModules.ArtsyNativeModule.clearUserData() : Promise.resolve(), + Platform.OS === "ios" + ? await LegacyNativeModules.ArtsyNativeModule.clearUserData() + : Promise.resolve(), await signOutGoogle(), CookieManager.clearAll(), RelayCache.clearAll(), diff --git a/src/lib/store/GlobalStore.tsx b/src/lib/store/GlobalStore.tsx index 88e12bf142c..1b5d9cc5033 100644 --- a/src/lib/store/GlobalStore.tsx +++ b/src/lib/store/GlobalStore.tsx @@ -110,7 +110,9 @@ export function useSelectedTab(): BottomTabType { return hooks.useStoreState((state) => state.bottomTabs.sessionState.selectedTab) } - const tabState = useNavigationState((state) => state.routes.find((r) => r.state?.type === "tab")?.state) + const tabState = useNavigationState( + (state) => state.routes.find((r) => r.state?.type === "tab")?.state + ) if (!tabState) { return "home" } else { @@ -213,7 +215,9 @@ export function unsafe__getSelectedTab(): BottomTabType { if (Platform.OS === "ios") { return globalStoreInstance().getState().bottomTabs.sessionState.selectedTab } - const tabState = __unsafe_mainModalStackRef.current?.getRootState().routes.find((r) => r.state?.type === "tab")?.state + const tabState = __unsafe_mainModalStackRef.current + ?.getRootState() + .routes.find((r) => r.state?.type === "tab")?.state if (!tabState) { return "home" } else { diff --git a/src/lib/store/GlobalStoreModel.tests.ts b/src/lib/store/GlobalStoreModel.tests.ts index 668c58c2f1a..01913cee78a 100644 --- a/src/lib/store/GlobalStoreModel.tests.ts +++ b/src/lib/store/GlobalStoreModel.tests.ts @@ -24,7 +24,9 @@ describe("GlobalStoreModel", () => { }, }) - expect(__globalStoreTestUtils__?.getCurrentState().search.recentSearches[0].props.displayLabel).toEqual("Banksy") + expect( + __globalStoreTestUtils__?.getCurrentState().search.recentSearches[0].props.displayLabel + ).toEqual("Banksy") }) it("can be manipulated", () => { @@ -36,7 +38,10 @@ describe("GlobalStoreModel", () => { store.sessionState.testStuff = ["wow", 8] }) // @ts-expect-error - expect(__globalStoreTestUtils__?.getCurrentState().sessionState.testStuff).toStrictEqual(["wow", 8]) + expect(__globalStoreTestUtils__?.getCurrentState().sessionState.testStuff).toStrictEqual([ + "wow", + 8, + ]) GlobalStore.actions.rehydrate({ sessionState: { @@ -45,7 +50,9 @@ describe("GlobalStoreModel", () => { }, }) // @ts-expect-error - expect(__globalStoreTestUtils__?.getCurrentState().sessionState.testStuff).toStrictEqual(["new stuff!"]) + expect(__globalStoreTestUtils__?.getCurrentState().sessionState.testStuff).toStrictEqual([ + "new stuff!", + ]) GlobalStore.actions.rehydrate({ sessionState: { @@ -54,7 +61,10 @@ describe("GlobalStoreModel", () => { }, }) // @ts-expect-error - expect(__globalStoreTestUtils__?.getCurrentState().sessionState.testStuff).toStrictEqual(["wow", "once again"]) + expect(__globalStoreTestUtils__?.getCurrentState().sessionState.testStuff).toStrictEqual([ + "wow", + "once again", + ]) GlobalStore.actions.__manipulate((store) => { // @ts-expect-error diff --git a/src/lib/store/GlobalStoreModel.ts b/src/lib/store/GlobalStoreModel.ts index d7eeebd7b30..6dc50087e87 100644 --- a/src/lib/store/GlobalStoreModel.ts +++ b/src/lib/store/GlobalStoreModel.ts @@ -1,15 +1,24 @@ import { Action, action, createStore, State, thunkOn, ThunkOn } from "easy-peasy" import { LegacyNativeModules } from "lib/NativeModules/LegacyNativeModules" import { BottomTabsModel, getBottomTabsModel } from "lib/Scenes/BottomTabs/BottomTabsModel" -import { getMyCollectionModel, MyCollectionModel } from "lib/Scenes/MyCollection/State/MyCollectionModel" +import { + getMyCollectionModel, + MyCollectionModel, +} from "lib/Scenes/MyCollection/State/MyCollectionModel" import { getSearchModel, SearchModel } from "lib/Scenes/Search/SearchModel" -import { getUserPreferencesModel, UserPreferencesModel } from "lib/Scenes/Search/UserPreferencesModel" +import { + getUserPreferencesModel, + UserPreferencesModel, +} from "lib/Scenes/Search/UserPreferencesModel" import { AuthModel, getAuthModel } from "./AuthModel" import { ConfigModel, getConfigModel } from "./ConfigModel" import { unsafe__getEnvironment } from "./GlobalStore" import { CURRENT_APP_VERSION } from "./migration" import { getNativeModel, NativeModel } from "./NativeModel" -import { getPendingPushNotificationModel, PendingPushNotificationModel } from "./PendingPushNotificationModel" +import { + getPendingPushNotificationModel, + PendingPushNotificationModel, +} from "./PendingPushNotificationModel" import { assignDeep, sanitize } from "./persistence" import { getToastModel, ToastModel } from "./ToastModel" import { getVisualClueModel, VisualClueModel } from "./VisualClueModel" diff --git a/src/lib/store/NativeModel.tests.ts b/src/lib/store/NativeModel.tests.ts index e45f8380d27..0670e425f12 100644 --- a/src/lib/store/NativeModel.tests.ts +++ b/src/lib/store/NativeModel.tests.ts @@ -9,11 +9,15 @@ beforeEach(() => { describe("NativeModel", () => { it(`triggers a fetch of the current unreadMessagesCount when a notification is received`, () => { - expect(__globalStoreTestUtils__?.getLastAction()?.type ?? "").not.toContain("fetchCurrentUnreadConversationCount") + expect(__globalStoreTestUtils__?.getLastAction()?.type ?? "").not.toContain( + "fetchCurrentUnreadConversationCount" + ) NotificationsManager.emit("event", { type: "NOTIFICATION_RECEIVED", } as NativeEvent) - expect(__globalStoreTestUtils__?.getLastAction().type).toContain("fetchCurrentUnreadConversationCount") + expect(__globalStoreTestUtils__?.getLastAction().type).toContain( + "fetchCurrentUnreadConversationCount" + ) }) describe("REQUEST_NAVIGATION", () => { diff --git a/src/lib/store/NativeModel.ts b/src/lib/store/NativeModel.ts index 90a5be34fc4..4f729338394 100644 --- a/src/lib/store/NativeModel.ts +++ b/src/lib/store/NativeModel.ts @@ -65,7 +65,9 @@ listenToNativeEvents((event: NativeEvent) => { switch (event.type) { case "IDENTIFY_TRACKING": // Segment should automatically stitch identify calls to existing user even if userid is null - SegmentTrackingProvider.identify ? SegmentTrackingProvider.identify(null, event.payload) : (() => undefined)() + SegmentTrackingProvider.identify + ? SegmentTrackingProvider.identify(null, event.payload) + : (() => undefined)() return case "EVENT_TRACKING": SegmentTrackingProvider.postEvent(event.payload) diff --git a/src/lib/store/PropsStore.ts b/src/lib/store/PropsStore.ts index f715365c886..e5666acbfb4 100644 --- a/src/lib/store/PropsStore.ts +++ b/src/lib/store/PropsStore.ts @@ -11,7 +11,11 @@ class PropsStore { PropsStore._instance = this } - updateProps(moduleName: string, props: any, callback?: (updatedProps: { [key: string]: any }) => void) { + updateProps( + moduleName: string, + props: any, + callback?: (updatedProps: { [key: string]: any }) => void + ) { this.mergeNewPropsForModule(moduleName, props) callback?.(this.propsByModuleName[moduleName]) } diff --git a/src/lib/store/config/EchoModel.tests.tsx b/src/lib/store/config/EchoModel.tests.tsx index 8f2fd2ef4f0..bec6d2dea2d 100644 --- a/src/lib/store/config/EchoModel.tests.tsx +++ b/src/lib/store/config/EchoModel.tests.tsx @@ -107,7 +107,9 @@ describe("Echo", () => { GlobalStore.actions.__manipulate((state) => { state.config.echo.state = echoConfig }) - expect(forceUpdateMessage()).toEqual("New app version required. Please update your Artsy app to continue.") + expect(forceUpdateMessage()).toEqual( + "New app version required. Please update your Artsy app to continue." + ) }) it("when the version number is exactly the minumum required version", () => { diff --git a/src/lib/store/config/EchoModel.tsx b/src/lib/store/config/EchoModel.tsx index 65883502da9..32faf3d7888 100644 --- a/src/lib/store/config/EchoModel.tsx +++ b/src/lib/store/config/EchoModel.tsx @@ -61,10 +61,14 @@ export const getEchoModel = (): EchoModel => ({ actions.fetchRemoteEcho() } ), - stripePublishableKey: computed([(_, store) => store.config.environment.env, (state) => state], (env, state) => { - const key = env === "production" ? "StripeProductionPublishableKey" : "StripeStagingPublishableKey" - return state.state.messages.find((e) => e.name === key)?.content! - }), + stripePublishableKey: computed( + [(_, store) => store.config.environment.env, (state) => state], + (env, state) => { + const key = + env === "production" ? "StripeProductionPublishableKey" : "StripeStagingPublishableKey" + return state.state.messages.find((e) => e.name === key)?.content! + } + ), forceUpdateMessage: computed((state) => { const appVersion = appJson().version const killedVersions = state.state.killedVersions diff --git a/src/lib/store/config/FeaturesModel.tests.tsx b/src/lib/store/config/FeaturesModel.tests.tsx index 6b0360cbeee..7c79af23182 100644 --- a/src/lib/store/config/FeaturesModel.tests.tsx +++ b/src/lib/store/config/FeaturesModel.tests.tsx @@ -41,9 +41,15 @@ jest.mock("lib/store/config/features", () => { }) const getComputedFeatures = () => - __globalStoreTestUtils__?.getCurrentState().config.features.flags as unknown as Record + __globalStoreTestUtils__?.getCurrentState().config.features.flags as unknown as Record< + TestFeatures, + boolean + > const getComputedDevToggles = () => - __globalStoreTestUtils__?.getCurrentState().config.features.devToggles as unknown as Record + __globalStoreTestUtils__?.getCurrentState().config.features.devToggles as unknown as Record< + TestDevToggles, + boolean + > describe("Feature flags", () => { it("are taken from the features definition map and turned into a computed boolean map in the global store", () => { diff --git a/src/lib/store/config/FeaturesModel.tsx b/src/lib/store/config/FeaturesModel.tsx index 0c556d6fc39..6126b2ca79c 100644 --- a/src/lib/store/config/FeaturesModel.tsx +++ b/src/lib/store/config/FeaturesModel.tsx @@ -7,7 +7,10 @@ export type DevToggleMap = { [k in DevToggleName]: boolean } export interface FeaturesModel { adminOverrides: { [k in FeatureName | DevToggleName]?: boolean } - setAdminOverride: Action + setAdminOverride: Action< + FeaturesModel, + { key: FeatureName | DevToggleName; value: boolean | null } + > // user features flags: Computed diff --git a/src/lib/store/config/features.ts b/src/lib/store/config/features.ts index 1b75276ea1c..e02e70d5117 100644 --- a/src/lib/store/config/features.ts +++ b/src/lib/store/config/features.ts @@ -26,7 +26,9 @@ export interface FeatureDescriptor { } // Helper function to get good typings and intellisense -function defineFeatures(featureMap: { readonly [featureName in T]: FeatureDescriptor }) { +function defineFeatures(featureMap: { + readonly [featureName in T]: FeatureDescriptor +}) { return featureMap } @@ -234,8 +236,9 @@ export interface DevToggleDescriptor { } // Helper function to get good typings and intellisense -const defineDevToggles = (devToggleMap: { readonly [devToggleName in T]: DevToggleDescriptor }) => - devToggleMap +const defineDevToggles = (devToggleMap: { + readonly [devToggleName in T]: DevToggleDescriptor +}) => devToggleMap export type DevToggleName = keyof typeof devToggles @@ -275,7 +278,5 @@ export const isDevToggle = (name: FeatureName | DevToggleName): name is DevToggl type Assert = U // If you mouse-over the name of the type below, you should be able to see the key that needs renaming! -export type _ThereIsAKeyThatIsCommonInFeaturesAndDevToggles_PleaseRename_MouseOverToSeeTheNaughtyKey = Assert< - never, - keyof (typeof features | typeof devToggles) -> +export type _ThereIsAKeyThatIsCommonInFeaturesAndDevToggles_PleaseRename_MouseOverToSeeTheNaughtyKey = + Assert diff --git a/src/lib/store/config/visualClues.ts b/src/lib/store/config/visualClues.ts index c93f3b63ee6..28cf23c3249 100644 --- a/src/lib/store/config/visualClues.ts +++ b/src/lib/store/config/visualClues.ts @@ -8,7 +8,9 @@ export interface VisualClueDescriptor { } // Helper function to get good typings and intellisense -function defineVisualClues(visualClueMap: { readonly [visualClueName in T]: VisualClueDescriptor }) { +function defineVisualClues(visualClueMap: { + readonly [visualClueName in T]: VisualClueDescriptor +}) { return visualClueMap } diff --git a/src/lib/store/migration.tests.ts b/src/lib/store/migration.tests.ts index 830e4490d47..2563d8e926d 100644 --- a/src/lib/store/migration.tests.ts +++ b/src/lib/store/migration.tests.ts @@ -9,7 +9,8 @@ jest.mock("lib/NativeModules/LegacyNativeModules", () => ({ LegacyNativeModules: { ...jest.requireActual("lib/NativeModules/LegacyNativeModules").LegacyNativeModules, ARNotificationsManager: { - ...jest.requireActual("lib/NativeModules/LegacyNativeModules").LegacyNativeModules.ARNotificationsManager, + ...jest.requireActual("lib/NativeModules/LegacyNativeModules").LegacyNativeModules + .ARNotificationsManager, nativeState: { userAgent: "Jest Unit Tests", authenticationToken: null, @@ -168,7 +169,9 @@ describe("artsy app store migrations", () => { } __globalStoreTestUtils__?.reset() - expect(migrate({ state: { version: 0 } })).toEqual(sanitize(__globalStoreTestUtils__?.getCurrentState())) + expect(migrate({ state: { version: 0 } })).toEqual( + sanitize(__globalStoreTestUtils__?.getCurrentState()) + ) }) it("CURRENT_APP_VERSION is always the latest one", () => { @@ -177,7 +180,9 @@ describe("artsy app store migrations", () => { it("Versions list starts from `1` and increases by `1`", () => { expect(_.min(Object.values(Versions))).toBe(1) - expect(Object.values(Versions).sort((a, b) => a - b)).toStrictEqual(_.range(1, Object.values(Versions).length + 1)) + expect(Object.values(Versions).sort((a, b) => a - b)).toStrictEqual( + _.range(1, Object.values(Versions).length + 1) + ) }) }) @@ -296,7 +301,9 @@ describe("App version Versions.RenameUserEmail", () => { previousState.native.sessionState = { userEmail: "user@ios.com" } - LegacyNativeModules.ARTemporaryAPIModule.getUserEmail = jest.fn(() => previousState.native.sessionState.userEmail) + LegacyNativeModules.ARTemporaryAPIModule.getUserEmail = jest.fn( + () => previousState.native.sessionState.userEmail + ) const migratedState = migrate({ state: previousState, toVersion: migrationToTest, diff --git a/src/lib/store/persistence.tests.ts b/src/lib/store/persistence.tests.ts index 63c29067a89..0aaa031df41 100644 --- a/src/lib/store/persistence.tests.ts +++ b/src/lib/store/persistence.tests.ts @@ -1,6 +1,13 @@ import AsyncStorage from "@react-native-community/async-storage" import { migrate } from "./migration" -import { assignDeep, LEGACY_SEARCH_STORAGE_KEY, persist, sanitize, STORAGE_KEY, unpersist } from "./persistence" +import { + assignDeep, + LEGACY_SEARCH_STORAGE_KEY, + persist, + sanitize, + STORAGE_KEY, + unpersist, +} from "./persistence" jest.mock("./migration", () => ({ migrate: jest.fn((a) => a.state) })) @@ -121,17 +128,23 @@ describe(persist, () => { require("@react-native-community/async-storage").__resetState() }) it("omits the sessionStorage key", async () => { - await persist({ bottomTabs: { selectedTab: "home", sessionState: { unreadConversationCount: 5 } } } as any) + await persist({ + bottomTabs: { selectedTab: "home", sessionState: { unreadConversationCount: 5 } }, + } as any) expect(JSON.parse((await AsyncStorage.getItem(STORAGE_KEY)) ?? "")).toEqual({ bottomTabs: { selectedTab: "home" }, }) }) it("overwrites the previous value", async () => { - await persist({ bottomTabs: { selectedTab: "home", sessionState: { unreadConversationCount: 5 } } } as any) + await persist({ + bottomTabs: { selectedTab: "home", sessionState: { unreadConversationCount: 5 } }, + } as any) expect(JSON.parse((await AsyncStorage.getItem(STORAGE_KEY)) ?? "")).toEqual({ bottomTabs: { selectedTab: "home" }, }) - await persist({ bottomTabs: { selectedTab: "explore", sessionState: { unreadConversationCount: 5 } } } as any) + await persist({ + bottomTabs: { selectedTab: "explore", sessionState: { unreadConversationCount: 5 } }, + } as any) expect(JSON.parse((await AsyncStorage.getItem(STORAGE_KEY)) ?? "")).toEqual({ bottomTabs: { selectedTab: "explore" }, }) @@ -182,7 +195,9 @@ describe(unpersist, () => { ]) ) - expect(await unpersist()).toMatchObject({ search: { recentSearches: [{ props: { displayLabel: "Banksy" } }] } }) + expect(await unpersist()).toMatchObject({ + search: { recentSearches: [{ props: { displayLabel: "Banksy" } }] }, + }) }) it("ignores corrupt legacy search state", async () => { @@ -196,11 +211,15 @@ describe(unpersist, () => { ) await AsyncStorage.setItem(LEGACY_SEARCH_STORAGE_KEY, "{: 0}") - expect((await unpersist()).search?.recentSearches?.[0]?.props?.displayLabel).toBe("i am a recent search") + expect((await unpersist()).search?.recentSearches?.[0]?.props?.displayLabel).toBe( + "i am a recent search" + ) await AsyncStorage.setItem(LEGACY_SEARCH_STORAGE_KEY, "{}") - expect((await unpersist()).search?.recentSearches?.[0]?.props?.displayLabel).toBe("i am a recent search") + expect((await unpersist()).search?.recentSearches?.[0]?.props?.displayLabel).toBe( + "i am a recent search" + ) }) it("loads legacy search state even if no existing app state was present", async () => { @@ -219,6 +238,8 @@ describe(unpersist, () => { ]) ) - expect(await unpersist()).toMatchObject({ search: { recentSearches: [{ props: { displayLabel: "Banksy" } }] } }) + expect(await unpersist()).toMatchObject({ + search: { recentSearches: [{ props: { displayLabel: "Banksy" } }] }, + }) }) }) diff --git a/src/lib/tests/MockRelayRenderer.tests.tsx b/src/lib/tests/MockRelayRenderer.tests.tsx index 104afe35050..f757a405c89 100644 --- a/src/lib/tests/MockRelayRenderer.tests.tsx +++ b/src/lib/tests/MockRelayRenderer.tests.tsx @@ -63,6 +63,8 @@ describe("MockRelayRenderer", () => { errorInfo: {}, }, }) - expect(tree.update().text()).toEqual("Error occurred while rendering Relay component: Error: Hey it's an error!") + expect(tree.update().text()).toEqual( + "Error occurred while rendering Relay component: Error: Hey it's an error!" + ) }) }) diff --git a/src/lib/tests/MockRelayRenderer.tsx b/src/lib/tests/MockRelayRenderer.tsx index 40c0b4c496d..cb7b4acb034 100644 --- a/src/lib/tests/MockRelayRenderer.tsx +++ b/src/lib/tests/MockRelayRenderer.tsx @@ -146,7 +146,9 @@ export class MockRelayRenderer extends React.Component< if (mockNetwork) { if (mockResolvers || mockData || mockMutationResults) { - throw new Error("You cannot use mockNetwork with mockResolvers, mockData, or mockMutationResults") + throw new Error( + "You cannot use mockNetwork with mockResolvers, mockData, or mockMutationResults" + ) } return mockNetwork } @@ -176,7 +178,8 @@ export class MockRelayRenderer extends React.Component< // to test this in a generic way, plus with the rule we get fixes. if (__TEST__ && QueryRenderer === require("../../../__mocks__/react-relay").QueryRenderer) { throw new Error( - "The `react-relay` module has been mocked, be sure to unmock it with: " + '`jest.unmock("react-relay")`' + "The `react-relay` module has been mocked, be sure to unmock it with: " + + '`jest.unmock("react-relay")`' ) } diff --git a/src/lib/tests/MockRelayRendererFixtures.tsx b/src/lib/tests/MockRelayRendererFixtures.tsx index 33a35f05585..6aee5c43f24 100644 --- a/src/lib/tests/MockRelayRendererFixtures.tsx +++ b/src/lib/tests/MockRelayRendererFixtures.tsx @@ -13,7 +13,9 @@ import { Image, Text, View } from "react-native" import { createFragmentContainer, graphql, QueryRenderer } from "react-relay" const Metadata = createFragmentContainer( - (props: { artworkMetadata: MockRelayRendererFixtures_artworkMetadata }) => {props.artworkMetadata.title}, + (props: { artworkMetadata: MockRelayRendererFixtures_artworkMetadata }) => ( + {props.artworkMetadata.title} + ), { artworkMetadata: graphql` fragment MockRelayRendererFixtures_artworkMetadata on Artwork { diff --git a/src/lib/tests/createMockNetworkLayer/createMockNetworkLayer.tests.tsx b/src/lib/tests/createMockNetworkLayer/createMockNetworkLayer.tests.tsx index 93c2f843ea0..a55921b84e0 100644 --- a/src/lib/tests/createMockNetworkLayer/createMockNetworkLayer.tests.tsx +++ b/src/lib/tests/createMockNetworkLayer/createMockNetworkLayer.tests.tsx @@ -5,7 +5,10 @@ import { createMockNetworkLayer2 } from "./index" jest.unmock("react-relay") describe("createMockNetworkLayer", () => { - function fetchQueryWithData(options: Parameters[0], query?: GraphQLTaggedNode) { + function fetchQueryWithData( + options: Parameters[0], + query?: GraphQLTaggedNode + ) { const network = createMockNetworkLayer2(options) const source = new RecordSource() @@ -102,6 +105,8 @@ describe("createMockNetworkLayer", () => { ` ) expect(data.artist.forSaleArtworks).toEqual({ edges: [{ node: { id: "for-sale-work" } }] }) - expect(data.artist.notForSaleArtworks).toEqual({ edges: [{ node: { id: "no-for-sale-work" } }] }) + expect(data.artist.notForSaleArtworks).toEqual({ + edges: [{ node: { id: "no-for-sale-work" } }], + }) }) }) diff --git a/src/lib/tests/createMockNetworkLayer/index.ts b/src/lib/tests/createMockNetworkLayer/index.ts index 9515794df72..829e63a7884 100644 --- a/src/lib/tests/createMockNetworkLayer/index.ts +++ b/src/lib/tests/createMockNetworkLayer/index.ts @@ -65,7 +65,8 @@ export const createMockFetchQuery = ({ const pathAsArray = responsePathAsArray(info.path) if (pathAsArray.length === 1) { // source is null for root fields - source = source || (info.operation.operation === "mutation" ? mockMutationResults : mockData) + source = + source || (info.operation.operation === "mutation" ? mockMutationResults : mockData) } // fail early if source is not an object type @@ -147,8 +148,13 @@ export const createMockFetchQuery = ({ Mutation: Object.keys(mockMutationResults).reduce( (acc, k) => ({ ...acc, + [k]: // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - [k]: typeof mockMutationResults[k] === "function" ? mockMutationResults[k] : () => mockMutationResults[k], + typeof mockMutationResults[k] === "function" + ? // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + mockMutationResults[k] + : // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + () => mockMutationResults[k], }), {} ), diff --git a/src/lib/tests/flushPromiseQueue.ts b/src/lib/tests/flushPromiseQueue.ts index d18e3d8c036..06d65396e3c 100644 --- a/src/lib/tests/flushPromiseQueue.ts +++ b/src/lib/tests/flushPromiseQueue.ts @@ -1,4 +1,5 @@ /** * test utility to wait for all promises to be resolved */ -export const flushPromiseQueue = () => new Promise((r) => setTimeout(() => requestAnimationFrame(r), 0)) +export const flushPromiseQueue = () => + new Promise((r) => setTimeout(() => requestAnimationFrame(r), 0)) diff --git a/src/lib/tests/globallyMockedStuff.ts b/src/lib/tests/globallyMockedStuff.ts index a9fabf828b0..7ba114fce10 100644 --- a/src/lib/tests/globallyMockedStuff.ts +++ b/src/lib/tests/globallyMockedStuff.ts @@ -1,6 +1,8 @@ import { postEventToProviders } from "lib/utils/track/providers" import { TrackingProp } from "react-tracking" -export const mockPostEventToProviders = postEventToProviders as jest.MockedFunction +export const mockPostEventToProviders = postEventToProviders as jest.MockedFunction< + typeof postEventToProviders +> export const mockTrackEvent = jest.fn() as jest.MockedFunction diff --git a/src/lib/tests/mockTracking.ts b/src/lib/tests/mockTracking.ts index b15d6a6e572..0c67efb4ab8 100644 --- a/src/lib/tests/mockTracking.ts +++ b/src/lib/tests/mockTracking.ts @@ -12,6 +12,8 @@ import track from "react-tracking" * and then make assertions like * expect(Events.postEvent).toHaveBeenCalledWith({myTrackingProperty: "whateve"}) */ -export function mockTracking(Component: React.ComponentType): React.ComponentType { +export function mockTracking( + Component: React.ComponentType +): React.ComponentType { return track({}, { dispatch: (data) => postEventToProviders(data) })(Component) } diff --git a/src/lib/tests/renderRelayTree.tsx b/src/lib/tests/renderRelayTree.tsx index 487f461ba10..341545d5279 100644 --- a/src/lib/tests/renderRelayTree.tsx +++ b/src/lib/tests/renderRelayTree.tsx @@ -15,8 +15,9 @@ import "./renderUntil" * need to use `renderUntil` directly, such as after making updates to a Relay * tree. */ -export const RelayFinishedLoading: RenderUntilPredicate = (tree: any /* STRICTNESS_MIGRATION */) => - !tree.find(`[testID="${LoadingTestID}"]`).length +export const RelayFinishedLoading: RenderUntilPredicate = ( + tree: any /* STRICTNESS_MIGRATION */ +) => !tree.find(`[testID="${LoadingTestID}"]`).length /** * Renders a tree of Relay containers with a mocked local instance of the diff --git a/src/lib/tests/renderUntil.tests.tsx b/src/lib/tests/renderUntil.tests.tsx index 17601ca49bf..00b968aa3d4 100644 --- a/src/lib/tests/renderUntil.tests.tsx +++ b/src/lib/tests/renderUntil.tests.tsx @@ -46,8 +46,10 @@ describe("renderUntil", () => { }) it("resolves the promise with an enzyme wrapper with the final state", async () => { - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const wrapper = await mount().renderUntil((tree) => tree.find(Text).text() !== "Loading") + const wrapper = await mount().renderUntil( + // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + (tree) => tree.find(Text).text() !== "Loading" + ) expect(wrapper.find(Text).text()).toEqual("ohai") }) }) diff --git a/src/lib/tests/setupTestWrapper.tsx b/src/lib/tests/setupTestWrapper.tsx index 0366de65b97..b35c4ae3f75 100644 --- a/src/lib/tests/setupTestWrapper.tsx +++ b/src/lib/tests/setupTestWrapper.tsx @@ -41,7 +41,9 @@ export const setupTestWrapperTL = ({ const view = render() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return view @@ -76,7 +78,9 @@ export const setupTestWrapper = ({ const wrapper = renderWithWrappers() act(() => { - env.mock.resolveMostRecentOperation((operation) => MockPayloadGenerator.generate(operation, mockResolvers)) + env.mock.resolveMostRecentOperation((operation) => + MockPayloadGenerator.generate(operation, mockResolvers) + ) }) return wrapper diff --git a/src/lib/utils/AboveTheFoldQueryRenderer.tsx b/src/lib/utils/AboveTheFoldQueryRenderer.tsx index b69291b9a03..ad32b1189e0 100644 --- a/src/lib/utils/AboveTheFoldQueryRenderer.tsx +++ b/src/lib/utils/AboveTheFoldQueryRenderer.tsx @@ -4,7 +4,10 @@ import { CacheConfig, GraphQLTaggedNode, OperationType } from "relay-runtime" import RelayModernEnvironment from "relay-runtime/lib/store/RelayModernEnvironment" import { renderWithPlaceholder } from "./renderWithPlaceholder" -interface AboveTheFoldQueryRendererProps { +interface AboveTheFoldQueryRendererProps< + AboveQuery extends OperationType, + BelowQuery extends OperationType +> { environment: RelayModernEnvironment above: { query: GraphQLTaggedNode @@ -15,7 +18,9 @@ interface AboveTheFoldQueryRendererProps) => React.ReactChild) + | (( + args: RenderArgs<{ above: AboveQuery["response"]; below: BelowQuery["response"] }> + ) => React.ReactChild) // convenience option for using `renderWithPlaceholder` logic without too much boilerplate | { renderComponent: (args: { @@ -42,9 +47,10 @@ interface RenderArgs { * in cases where the 'below-the-fold' content adds significant time to the query duration. * @param props */ -export function AboveTheFoldQueryRenderer( - props: AboveTheFoldQueryRendererProps -) { +export function AboveTheFoldQueryRenderer< + AboveQuery extends OperationType, + BelowQuery extends OperationType +>(props: AboveTheFoldQueryRendererProps) { const [aboveArgs, setAboveArgs] = useState>(null) const [belowArgs, setBelowArgs] = useState>(null) // We want to debounce the initial render in case there is a cache hit for both queries @@ -108,7 +114,9 @@ export function AboveTheFoldQueryRenderer description ?? k ).map(([k]) => k as FeatureName) -const configurableDevToggleKeys = sortBy(Object.entries(devToggles), ([k, { description }]) => description ?? k).map( - ([k]) => k as DevToggleName -) +const configurableDevToggleKeys = sortBy( + Object.entries(devToggles), + ([k, { description }]) => description ?? k +).map(([k]) => k as DevToggleName) export const AdminMenu: React.FC<{ onClose(): void }> = ({ onClose = dismissModal }) => { const migrationVersion = GlobalStore.useAppState((s) => s.version) - const server = GlobalStore.useAppState((s) => s.config.environment.strings.webURL).slice("https://".length) + const server = GlobalStore.useAppState((s) => s.config.environment.strings.webURL).slice( + "https://".length + ) useEffect( React.useCallback(() => { @@ -123,9 +137,15 @@ export const AdminMenu: React.FC<{ onClose(): void }> = ({ onClose = dismissModa title="Migration version" rightView={ - GlobalStore.actions._setVersion(migrationVersion - 1)} /> + GlobalStore.actions._setVersion(migrationVersion - 1)} + /> {migrationVersion} - GlobalStore.actions._setVersion(migrationVersion + 1)} /> + GlobalStore.actions._setVersion(migrationVersion + 1)} + /> } /> @@ -141,7 +161,10 @@ export const AdminMenu: React.FC<{ onClose(): void }> = ({ onClose = dismissModa Keychain.resetInternetCredentials(server) }} /> - NativeModules.DevMenu.show()} /> + NativeModules.DevMenu.show()} + /> { @@ -344,10 +367,14 @@ function envMenuOption( const EnvironmentOptions: React.FC<{ onClose: () => void }> = ({ onClose }) => { const color = useColor() - const { env, adminOverrides, strings } = GlobalStore.useAppState((store) => store.config.environment) + const { env, adminOverrides, strings } = GlobalStore.useAppState( + (store) => store.config.environment + ) // show custom url options if there are already admin overrides in effect, or if the user has tapped the option // to set custom overrides during the lifetime of this component - const [showCustomURLOptions, setShowCustomURLOptions] = useState(Object.keys(adminOverrides).length > 0) + const [showCustomURLOptions, setShowCustomURLOptions] = useState( + Object.keys(adminOverrides).length > 0 + ) return ( <> void }> = ({ onClose }) => { undefined, compact([ envMenuOption("staging", env, showCustomURLOptions, setShowCustomURLOptions, onClose), - envMenuOption("production", env, showCustomURLOptions, setShowCustomURLOptions, onClose), + envMenuOption( + "production", + env, + showCustomURLOptions, + setShowCustomURLOptions, + onClose + ), { text: "Cancel", style: "destructive", @@ -382,13 +415,23 @@ const EnvironmentOptions: React.FC<{ onClose: () => void }> = ({ onClose }) => { Object.entries(presets).map(([name, value]) => ({ text: name, onPress: () => { - GlobalStore.actions.config.environment.setAdminOverride({ key: key as EnvironmentKey, value }) + GlobalStore.actions.config.environment.setAdminOverride({ + key: key as EnvironmentKey, + value, + }) }, })) ) }} > - + {description} @@ -415,7 +458,14 @@ export const FeatureFlagMenuItem: React.FC<{ const color = useColor() return ( - + {title} diff --git a/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tests.tsx b/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tests.tsx index 1bf1c74d5dc..c84f3f0a824 100644 --- a/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tests.tsx +++ b/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tests.tsx @@ -1,5 +1,8 @@ import { reducer } from "lib/utils/ArtworkInquiry/ArtworkInquiryStore" -import { ArtworkInquiryActions, ArtworkInquiryContextState } from "lib/utils/ArtworkInquiry/ArtworkInquiryTypes" +import { + ArtworkInquiryActions, + ArtworkInquiryContextState, +} from "lib/utils/ArtworkInquiry/ArtworkInquiryTypes" import { InquiryOptions } from "lib/utils/ArtworkInquiry/ArtworkInquiryTypes" let inquiryState: ArtworkInquiryContextState diff --git a/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tsx b/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tsx index e148be4ccc8..ff478571d4e 100644 --- a/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tsx +++ b/src/lib/utils/ArtworkInquiry/ArtworkInquiryStore.tsx @@ -64,5 +64,9 @@ export const ArtworkInquiryStateProvider = ({ children }: any) => { reducer, initialArtworkInquiryState ) - return {children} + return ( + + {children} + + ) } diff --git a/src/lib/utils/ArtworkInquiry/ArtworkInquiryTypes.ts b/src/lib/utils/ArtworkInquiry/ArtworkInquiryTypes.ts index 5bd719eb720..0c2120f2e9e 100644 --- a/src/lib/utils/ArtworkInquiry/ArtworkInquiryTypes.ts +++ b/src/lib/utils/ArtworkInquiry/ArtworkInquiryTypes.ts @@ -2,7 +2,12 @@ import { InquiryQuestionInput } from "__generated__/SubmitInquiryRequestMutation import { Dispatch } from "react" import { LocationWithDetails } from "../googleMaps" -export type ArtworkInquiryActions = SelectInquiryType | SelectLocation | SelectInquiryQuestion | SetMessage | ResetForm +export type ArtworkInquiryActions = + | SelectInquiryType + | SelectLocation + | SelectInquiryQuestion + | SetMessage + | ResetForm export interface ArtworkInquiryContextProps { state: ArtworkInquiryContextState diff --git a/src/lib/utils/NetworkAwareProvider.tsx b/src/lib/utils/NetworkAwareProvider.tsx index 221e3ea8d64..a3021adf731 100644 --- a/src/lib/utils/NetworkAwareProvider.tsx +++ b/src/lib/utils/NetworkAwareProvider.tsx @@ -31,7 +31,13 @@ export const NetworkAwareProvider: React.FC<{}> = () => { presentationStyle="overFullScreen" > - + Connection Error diff --git a/src/lib/utils/PushNotification.tests.ts b/src/lib/utils/PushNotification.tests.ts index ccd79d70667..9c5fd23f345 100644 --- a/src/lib/utils/PushNotification.tests.ts +++ b/src/lib/utils/PushNotification.tests.ts @@ -84,7 +84,10 @@ describe("Push Notification Tests", () => { const notification = { channelId: "fcm_fallback_notification_channel", color: null, - data: { url: "https://www.artsy.net/artwork/fabrice-monteiro-signares-number-3-goree", id: "0" }, + data: { + url: "https://www.artsy.net/artwork/fabrice-monteiro-signares-number-3-goree", + id: "0", + }, finish: () => { // }, @@ -103,12 +106,12 @@ describe("Push Notification Tests", () => { it("Saves tapped notification When a user is not logged in", () => { Push.handleReceivedNotification(notification) - expect(__globalStoreTestUtils__?.getCurrentState().pendingPushNotification.notification).toHaveProperty( - "tappedAt" - ) - expect(__globalStoreTestUtils__?.getCurrentState().pendingPushNotification.notification?.data).toEqual( - notification.data - ) + expect( + __globalStoreTestUtils__?.getCurrentState().pendingPushNotification.notification + ).toHaveProperty("tappedAt") + expect( + __globalStoreTestUtils__?.getCurrentState().pendingPushNotification.notification?.data + ).toEqual(notification.data) // notification is not handled expect(navigate).not.toHaveBeenCalled() }) @@ -150,7 +153,8 @@ describe("Push Notification Tests", () => { it("Pending Notification: navigates to appropriate screen when called", () => { Push.handleReceivedNotification(notification) - const pendingNotification = __globalStoreTestUtils__?.getCurrentState().pendingPushNotification.notification + const pendingNotification = + __globalStoreTestUtils__?.getCurrentState().pendingPushNotification.notification Push.handlePendingNotification(pendingNotification as PendingPushNotification) expect(navigate).toHaveBeenNthCalledWith(1, notification.data.url, { passProps: notification.data, diff --git a/src/lib/utils/PushNotification.ts b/src/lib/utils/PushNotification.ts index 3750bdb8221..781559c1324 100644 --- a/src/lib/utils/PushNotification.ts +++ b/src/lib/utils/PushNotification.ts @@ -150,7 +150,9 @@ export const handlePendingNotification = (notification: PendingPushNotification GlobalStore.actions.pendingPushNotification.setPendingPushNotification(null) } -export const handleReceivedNotification = (notification: Omit) => { +export const handleReceivedNotification = ( + notification: Omit +) => { if (__DEV__ && !__TEST__) { console.log("RECIEVED NOTIFICATION", notification) } @@ -238,12 +240,16 @@ export async function configure() { export const getNotificationPermissionsStatus = (): Promise => { return new Promise((resolve) => { if (Platform.OS === "ios") { - LegacyNativeModules.ARTemporaryAPIModule.fetchNotificationPermissions((_, result: PushAuthorizationStatus) => { - resolve(result) - }) + LegacyNativeModules.ARTemporaryAPIModule.fetchNotificationPermissions( + (_, result: PushAuthorizationStatus) => { + resolve(result) + } + ) } else if (Platform.OS === "android") { PushNotification.checkPermissions((permissions) => { - resolve(permissions.alert ? PushAuthorizationStatus.Authorized : PushAuthorizationStatus.Denied) + resolve( + permissions.alert ? PushAuthorizationStatus.Authorized : PushAuthorizationStatus.Denied + ) }) } }) diff --git a/src/lib/utils/QAInfo.tsx b/src/lib/utils/QAInfo.tsx index 349bac49c9a..a6ccc02da5f 100644 --- a/src/lib/utils/QAInfo.tsx +++ b/src/lib/utils/QAInfo.tsx @@ -4,7 +4,9 @@ import { useDevToggle } from "lib/store/GlobalStore" import { Flex, FlexProps, Text, Touchable, useColor } from "palette" import React from "react" -export const QAInfoPanel: React.FC & { info: Array<[string, string]> }> = (props) => ( +export const QAInfoPanel: React.FC< + Omit & { info: Array<[string, string]> } +> = (props) => ( {props.info.map(([key, value]) => ( diff --git a/src/lib/utils/__legacy_do_not_use__navigator-ios-shim.tsx b/src/lib/utils/__legacy_do_not_use__navigator-ios-shim.tsx index 7559a86a8d0..de6eb92d719 100644 --- a/src/lib/utils/__legacy_do_not_use__navigator-ios-shim.tsx +++ b/src/lib/utils/__legacy_do_not_use__navigator-ios-shim.tsx @@ -13,7 +13,10 @@ interface ScreenProps { const ScreenWrapper: React.FC<{ route: { params: ScreenProps } }> = (props) => { return ( - + ) } @@ -45,7 +48,11 @@ class NavigatorIOS extends React.Component<{ return ( (this.navigator = ref)} independent> - + ) diff --git a/src/lib/utils/artworkMediumCategories.tests.ts b/src/lib/utils/artworkMediumCategories.tests.ts index 37630ade385..29f8d663255 100644 --- a/src/lib/utils/artworkMediumCategories.tests.ts +++ b/src/lib/utils/artworkMediumCategories.tests.ts @@ -2,7 +2,9 @@ import { artworkMediumCategories } from "./artworkMediumCategories" describe("artworkMediumCategories", () => { it("maps raw (Gravity) artwork category labels to their respective values", () => { - expect(artworkMediumCategories.reduce((acc, cur) => ({ ...acc, [cur.value]: cur.label }), {})).toEqual({ + expect( + artworkMediumCategories.reduce((acc, cur) => ({ ...acc, [cur.value]: cur.label }), {}) + ).toEqual({ Architecture: "Architecture", "Design/Decorative Art": "Design/Decorative Art", "Drawing, Collage or other Work on Paper": "Drawing, Collage or other Work on Paper", diff --git a/src/lib/utils/artworkMediumCategories.ts b/src/lib/utils/artworkMediumCategories.ts index 9e8228df0fc..2533fdfe4d6 100644 --- a/src/lib/utils/artworkMediumCategories.ts +++ b/src/lib/utils/artworkMediumCategories.ts @@ -8,7 +8,10 @@ export const artworkMediumCategories: Medium[] = [ { label: "Sculpture", value: "Sculpture" }, { label: "Photography", value: "Photography" }, { label: "Print", value: "Print" }, - { label: "Drawing, Collage or other Work on Paper", value: "Drawing, Collage or other Work on Paper" }, + { + label: "Drawing, Collage or other Work on Paper", + value: "Drawing, Collage or other Work on Paper", + }, { label: "Mixed Media", value: "Mixed Media" }, { label: "Performance Art", value: "Performance Art" }, { label: "Installation", value: "Installation" }, diff --git a/src/lib/utils/artworkRarityClassifications.ts b/src/lib/utils/artworkRarityClassifications.ts index a98518f6287..222d06e37f6 100644 --- a/src/lib/utils/artworkRarityClassifications.ts +++ b/src/lib/utils/artworkRarityClassifications.ts @@ -9,7 +9,8 @@ export const artworkRarityClassifications = [ name: "Limited edition", label: "Limited Edition", value: "LIMITED_EDITION", - description: "The edition run has ended; the number of works produced is known and included in the listing.", + description: + "The edition run has ended; the number of works produced is known and included in the listing.", }, { name: "Open edition", diff --git a/src/lib/utils/convertCityToGeoJSON.ts b/src/lib/utils/convertCityToGeoJSON.ts index 4076ddc22c2..f616f55b4e6 100644 --- a/src/lib/utils/convertCityToGeoJSON.ts +++ b/src/lib/utils/convertCityToGeoJSON.ts @@ -18,8 +18,12 @@ import { Fair, Show } from "lib/Scenes/Map/types" // }, // } -export type FairsEdge = NonNullable["fairs"]>["edges"]> -export type ShowsEdge = NonNullable["shows"]>["edges"]> +export type FairsEdge = NonNullable< + NonNullable["fairs"]>["edges"] +> +export type ShowsEdge = NonNullable< + NonNullable["shows"]>["edges"] +> export const showsToGeoCityShow = (edges: Show[]): Show[] => edges.map((node) => { diff --git a/src/lib/utils/experiments.ts b/src/lib/utils/experiments.ts index e2c93aa16d0..eac1aebb026 100644 --- a/src/lib/utils/experiments.ts +++ b/src/lib/utils/experiments.ts @@ -11,7 +11,9 @@ export interface ExperimentDescriptor { } // Helper function to get good typings and intellisense -function defineExperiments(expirmentMap: { readonly [experimentName in T]: ExperimentDescriptor }) { +function defineExperiments(expirmentMap: { + readonly [experimentName in T]: ExperimentDescriptor +}) { return expirmentMap } diff --git a/src/lib/utils/extractNodes.tests.ts b/src/lib/utils/extractNodes.tests.ts index b5c492fab46..79c28e51fc4 100644 --- a/src/lib/utils/extractNodes.tests.ts +++ b/src/lib/utils/extractNodes.tests.ts @@ -2,12 +2,16 @@ import { extractNodes } from "./extractNodes" describe(extractNodes, () => { it(`extracts nodes from a connection`, async () => { - const connection = { edges: [{ node: { char: "A" } }, { node: { char: "B" } }, { node: { char: "C" } }] } + const connection = { + edges: [{ node: { char: "A" } }, { node: { char: "B" } }, { node: { char: "C" } }], + } expect(extractNodes(connection)).toEqual([{ char: "A" }, { char: "B" }, { char: "C" }]) }) it(`extracts nodes from a connection with a mapping function`, async () => { - const connection = { edges: [{ node: { char: "A" } }, { node: { char: "B" } }, { node: { char: "C" } }] } + const connection = { + edges: [{ node: { char: "A" } }, { node: { char: "B" } }, { node: { char: "C" } }], + } expect(extractNodes(connection, (node) => node.char).join("")).toEqual("ABC") }) diff --git a/src/lib/utils/extractNodes.ts b/src/lib/utils/extractNodes.ts index 7708e6dd8b9..43185dd5a9d 100644 --- a/src/lib/utils/extractNodes.ts +++ b/src/lib/utils/extractNodes.ts @@ -1,9 +1,13 @@ export function extractNodes( - connection: { readonly edges?: ReadonlyArray<{ readonly node?: Node | null } | null> | null } | undefined | null, + connection: + | { readonly edges?: ReadonlyArray<{ readonly node?: Node | null } | null> | null } + | undefined + | null, mapper?: (node: Node) => T ): T[] { return ( - connection?.edges?.map((edge) => (mapper ? (mapper(edge?.node!) as any) : edge?.node!)).filter((x) => x != null) ?? - [] + connection?.edges + ?.map((edge) => (mapper ? (mapper(edge?.node!) as any) : edge?.node!)) + .filter((x) => x != null) ?? [] ) } diff --git a/src/lib/utils/formatLargeNumberOfItems.tests.ts b/src/lib/utils/formatLargeNumberOfItems.tests.ts index cdcadde205e..14bb4e1ce85 100644 --- a/src/lib/utils/formatLargeNumberOfItems.tests.ts +++ b/src/lib/utils/formatLargeNumberOfItems.tests.ts @@ -18,22 +18,24 @@ describe(formatLargeNumberOfItems, () => { describe("custom pluralization", () => { it("formats a single item", () => { - expect(formatLargeNumberOfItems(1, "work for sale", "works for sale")).toMatchInlineSnapshot(`"1 work for sale"`) + expect(formatLargeNumberOfItems(1, "work for sale", "works for sale")).toMatchInlineSnapshot( + `"1 work for sale"` + ) }) it("formats less than a thousand", () => { - expect(formatLargeNumberOfItems(850, "work for sale", "works for sale")).toMatchInlineSnapshot( - `"850 works for sale"` - ) + expect( + formatLargeNumberOfItems(850, "work for sale", "works for sale") + ).toMatchInlineSnapshot(`"850 works for sale"`) }) it("formats more than a thousand less than a million", () => { - expect(formatLargeNumberOfItems(151000, "work for sale", "works for sale")).toMatchInlineSnapshot( - `"151.0k works for sale"` - ) + expect( + formatLargeNumberOfItems(151000, "work for sale", "works for sale") + ).toMatchInlineSnapshot(`"151.0k works for sale"`) }) it("formats more than a million", () => { - expect(formatLargeNumberOfItems(2200000, "work for sale", "works for sale")).toMatchInlineSnapshot( - `"2.2M works for sale"` - ) + expect( + formatLargeNumberOfItems(2200000, "work for sale", "works for sale") + ).toMatchInlineSnapshot(`"2.2M works for sale"`) }) }) }) diff --git a/src/lib/utils/general.ts b/src/lib/utils/general.ts index b435dcbac68..d6a36bddfaa 100644 --- a/src/lib/utils/general.ts +++ b/src/lib/utils/general.ts @@ -1 +1,2 @@ -export const isArtsyEmail = (email: string) => email.endsWith("@artsymail.com") || email.endsWith("@artsy.net") +export const isArtsyEmail = (email: string) => + email.endsWith("@artsymail.com") || email.endsWith("@artsy.net") diff --git a/src/lib/utils/get.ts b/src/lib/utils/get.ts index a523884149b..5a447c6aa8c 100644 --- a/src/lib/utils/get.ts +++ b/src/lib/utils/get.ts @@ -7,7 +7,11 @@ * @param unsafeDataOperation Function that returns the deep property * @param valueIfFailOrUndefined Value to return in case if there is no such property */ -export function get(obj: O, unsafeDataOperation: (x: O) => T, valueIfFailOrUndefined?: T): T | undefined { +export function get( + obj: O, + unsafeDataOperation: (x: O) => T, + valueIfFailOrUndefined?: T +): T | undefined { try { const result = unsafeDataOperation(obj) if (result) { diff --git a/src/lib/utils/getConvertedImageUrlFromS3.tsx b/src/lib/utils/getConvertedImageUrlFromS3.tsx index d9cf5d30ca1..8b8544a8f30 100644 --- a/src/lib/utils/getConvertedImageUrlFromS3.tsx +++ b/src/lib/utils/getConvertedImageUrlFromS3.tsx @@ -8,7 +8,10 @@ export async function getConvertedImageUrlFromS3(imagePath: string) { const convectionKey = await getConvectionGeminiKey() const acl = "private" - const assetCredentials = await getGeminiCredentialsForEnvironment({ acl, name: convectionKey || "" }) + const assetCredentials = await getGeminiCredentialsForEnvironment({ + acl, + name: convectionKey || "", + }) const bucket = assetCredentials.policyDocument.conditions.bucket const s3 = await uploadFileToS3(imagePath, acl, assetCredentials) return `https://${bucket}.s3.amazonaws.com/${s3.key}` diff --git a/src/lib/utils/getOrderStatus.ts b/src/lib/utils/getOrderStatus.ts index d7f5a76673e..07eff38bf46 100644 --- a/src/lib/utils/getOrderStatus.ts +++ b/src/lib/utils/getOrderStatus.ts @@ -1,12 +1,24 @@ -import { CommerceOrderStateEnum, OrderDetailsHeader_info } from "__generated__/OrderDetailsHeader_info.graphql" +import { + CommerceOrderStateEnum, + OrderDetailsHeader_info, +} from "__generated__/OrderDetailsHeader_info.graphql" import { OrderHistoryRowLineItem } from "./getTrackingUrl" export type OrderDetailsHeaderLineItem = NonNullable< NonNullable["edges"]>[0] >["node"] -export type OrderState = Exclude -export type ShipmentStatus = "PENDING" | "CONFIRMED" | "COLLECTED" | "IN_TRANSIT" | "COMPLETED" | "CANCELED" +export type OrderState = Exclude< + CommerceOrderStateEnum, + "ABANDONED" | "PENDING" | "%future added value" +> +export type ShipmentStatus = + | "PENDING" + | "CONFIRMED" + | "COLLECTED" + | "IN_TRANSIT" + | "COMPLETED" + | "CANCELED" enum ORDER_STATUSES { Pending = "Pending", diff --git a/src/lib/utils/getTrackingUrl.tests.ts b/src/lib/utils/getTrackingUrl.tests.ts index 20fd19fc2da..3ce7304e220 100644 --- a/src/lib/utils/getTrackingUrl.tests.ts +++ b/src/lib/utils/getTrackingUrl.tests.ts @@ -66,7 +66,8 @@ describe(getTrackingUrl, () => { mockOrderLineItem = { shipment: { trackingNumber: null, - trackingUrl: "https://www.ups.com/track?loc=en_us&tracknum=1zw475770393992448&Requester=NS/trackdetails", + trackingUrl: + "https://www.ups.com/track?loc=en_us&tracknum=1zw475770393992448&Requester=NS/trackdetails", }, fulfillments: { edges: [ diff --git a/src/lib/utils/getUrgencyTag.ts b/src/lib/utils/getUrgencyTag.ts index 5e64055e2f5..db0c7914493 100644 --- a/src/lib/utils/getUrgencyTag.ts +++ b/src/lib/utils/getUrgencyTag.ts @@ -22,7 +22,8 @@ export const getUrgencyTag = (endAt: string | null | undefined): string | null = return null } - const unit = timeUntilSaleEnd.duration === 1 ? timeUntilSaleEnd.unit.slice(0, -1) : timeUntilSaleEnd.unit + const unit = + timeUntilSaleEnd.duration === 1 ? timeUntilSaleEnd.unit.slice(0, -1) : timeUntilSaleEnd.unit return `${timeUntilSaleEnd.duration} ${unit} left` } diff --git a/src/lib/utils/googleMaps.ts b/src/lib/utils/googleMaps.ts index b0eb6872e5f..2ead71ed90d 100644 --- a/src/lib/utils/googleMaps.ts +++ b/src/lib/utils/googleMaps.ts @@ -31,7 +31,9 @@ export const getLocationPredictions = async (query: string): Promise => { +export const getLocationDetails = async ({ + id, + name, +}: SimpleLocation): Promise => { const queryString = stringify({ key: API_KEY, placeid: id, }) - const response = await fetch("https://maps.googleapis.com/maps/api/place/details/json?" + queryString) + const response = await fetch( + "https://maps.googleapis.com/maps/api/place/details/json?" + queryString + ) const data = await response.json() // TODO: Add dedicated error handling to the maps response const { address_components, geometry } = data.result as PlaceResult const cityPlace = address_components.find((comp) => comp.types[0] === "locality") - const statePlace = address_components.find((comp) => comp.types[0] === "administrative_area_level_1") + const statePlace = address_components.find( + (comp) => comp.types[0] === "administrative_area_level_1" + ) const countryPlace = address_components.find((comp) => comp.types[0] === "country") const postalCodePlace = address_components.find((comp) => comp.types[0] === "postal_code") const { lat, lng } = geometry.location diff --git a/src/lib/utils/hideBackButtonOnScroll.tests.tsx b/src/lib/utils/hideBackButtonOnScroll.tests.tsx index e2b1c7dab5f..7e7231caa8b 100644 --- a/src/lib/utils/hideBackButtonOnScroll.tests.tsx +++ b/src/lib/utils/hideBackButtonOnScroll.tests.tsx @@ -3,7 +3,10 @@ import { unsafe__getSelectedTab } from "lib/store/GlobalStore" import { createHideBackButtonOnScroll } from "lib/utils/hideBackButtonOnScroll" const hideBackButtonOnScroll = createHideBackButtonOnScroll((shouldHide) => - LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton(shouldHide, unsafe__getSelectedTab()) + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton( + shouldHide, + unsafe__getSelectedTab() + ) ) function event( @@ -14,38 +17,56 @@ function event( describe(hideBackButtonOnScroll, () => { beforeEach(() => { - hideBackButtonOnScroll(event({ target: Math.random(), nativeEvent: { contentOffset: { y: 0 } } })) - ;(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton as jest.Mock).mockReset() + hideBackButtonOnScroll( + event({ target: Math.random(), nativeEvent: { contentOffset: { y: 0 } } }) + ) + ;( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton as jest.Mock + ).mockReset() }) it("hides the back button when the user scrolls down far enough", () => { // get going hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 40 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).not.toHaveBeenCalled() + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).not.toHaveBeenCalled() // scroll down far hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 150 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).toHaveBeenCalledWith(true, "home") + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).toHaveBeenCalledWith(true, "home") }) it("shows the back button when the user scrolls back up", () => { hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 40 } } })) hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 660 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).toHaveBeenCalledWith(true, "home") + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).toHaveBeenCalledWith(true, "home") // need to change direction first hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 650 } } })) hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 400 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).toHaveBeenCalledWith(false, "home") + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).toHaveBeenCalledWith(false, "home") }) it("always shows the back button when the user is near the top of the scroll view", () => { hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 1 } } })) hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 45 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).toHaveBeenCalledWith(false, "home") + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).toHaveBeenCalledWith(false, "home") hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 55 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).toHaveBeenCalledWith(true, "home") + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).toHaveBeenCalledWith(true, "home") hideBackButtonOnScroll(event({ nativeEvent: { contentOffset: { y: 45 } } })) - expect(LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton).toHaveBeenCalledWith(false, "home") + expect( + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton + ).toHaveBeenCalledWith(false, "home") }) }) diff --git a/src/lib/utils/hideBackButtonOnScroll.tsx b/src/lib/utils/hideBackButtonOnScroll.tsx index 8397dbeff6c..608051b2b70 100644 --- a/src/lib/utils/hideBackButtonOnScroll.tsx +++ b/src/lib/utils/hideBackButtonOnScroll.tsx @@ -49,7 +49,10 @@ export const createHideBackButtonOnScroll: ( // then show the back button if the user has scrolled up far enough updateShouldHideBackButton(false) return - } else if (direction === "down" && yOffset - offsetWhenDirectionChanged > SCROLL_DOWN_TO_HIDE_THRESHOLD) { + } else if ( + direction === "down" && + yOffset - offsetWhenDirectionChanged > SCROLL_DOWN_TO_HIDE_THRESHOLD + ) { // hide the back button if the user has scrolled down far enough updateShouldHideBackButton(true) return @@ -60,7 +63,10 @@ export const createHideBackButtonOnScroll: ( export function useUpdadeShouldHideBackButton() { if (Platform.OS === "ios") { return (shouldHide: boolean) => - LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton(shouldHide, unsafe__getSelectedTab()) + LegacyNativeModules.ARScreenPresenterModule.updateShouldHideBackButton( + shouldHide, + unsafe__getSelectedTab() + ) } else { return useContext(LegacyBackButtonContext).updateShouldHideBackButton } diff --git a/src/lib/utils/isCloseToBottom.ts b/src/lib/utils/isCloseToBottom.ts index ee20989cdd4..cd1856fcb6f 100644 --- a/src/lib/utils/isCloseToBottom.ts +++ b/src/lib/utils/isCloseToBottom.ts @@ -23,7 +23,10 @@ const PAGE_END_THRESHOLD = 1000 type CallBack = () => void -export function isCloseToBottom(onScrollEnd: CallBack, pageEndThreshold: number = PAGE_END_THRESHOLD) { +export function isCloseToBottom( + onScrollEnd: CallBack, + pageEndThreshold: number = PAGE_END_THRESHOLD +) { const state = { sentEndForContentLength: 0 } interface ScrollEventProps { diff --git a/src/lib/utils/isCloseToEdge.ts b/src/lib/utils/isCloseToEdge.ts index 90001a224b5..dd6b58d2288 100644 --- a/src/lib/utils/isCloseToEdge.ts +++ b/src/lib/utils/isCloseToEdge.ts @@ -21,7 +21,10 @@ const PAGE_END_THRESHOLD = 1000 type CallBack = () => void -export function isCloseToEdge(onScrollEnd: CallBack, pageEndThreshold: number = PAGE_END_THRESHOLD) { +export function isCloseToEdge( + onScrollEnd: CallBack, + pageEndThreshold: number = PAGE_END_THRESHOLD +) { const state = { sentEndForContentLength: 0 } interface ScrollEventProps { diff --git a/src/lib/utils/normalizeText.ts b/src/lib/utils/normalizeText.ts index 390102d4b66..d9bf21dcbfc 100644 --- a/src/lib/utils/normalizeText.ts +++ b/src/lib/utils/normalizeText.ts @@ -27,8 +27,15 @@ const defaultDiacriticsRemovalMap = [ { base: "AV", letters: "\uA738\uA73A" }, { base: "AY", letters: "\uA73C" }, { base: "B", letters: "\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181" }, - { base: "C", letters: "\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E" }, - { base: "D", letters: "\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0" }, + { + base: "C", + letters: "\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E", + }, + { + base: "D", + letters: + "\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0", + }, { base: "DZ", letters: "\u01F1\u01C4" }, { base: "Dz", letters: "\u01F2\u01C5" }, { @@ -37,15 +44,25 @@ const defaultDiacriticsRemovalMap = [ "\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E", }, { base: "F", letters: "\u0046\u24BB\uFF26\u1E1E\u0191\uA77B" }, - { base: "G", letters: "\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E" }, - { base: "H", letters: "\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D" }, + { + base: "G", + letters: + "\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E", + }, + { + base: "H", + letters: "\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D", + }, { base: "I", letters: "\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197", }, { base: "J", letters: "\u004A\u24BF\uFF2A\u0134\u0248" }, - { base: "K", letters: "\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2" }, + { + base: "K", + letters: "\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2", + }, { base: "L", letters: @@ -56,7 +73,8 @@ const defaultDiacriticsRemovalMap = [ { base: "M", letters: "\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C" }, { base: "N", - letters: "\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4", + letters: + "\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4", }, { base: "NJ", letters: "\u01CA" }, { base: "Nj", letters: "\u01CB" }, @@ -74,13 +92,19 @@ const defaultDiacriticsRemovalMap = [ { base: "Q", letters: "\u0051\u24C6\uFF31\uA756\uA758\u024A" }, { base: "R", - letters: "\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782", + letters: + "\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782", }, { base: "S", - letters: "\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784", + letters: + "\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784", + }, + { + base: "T", + letters: + "\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786", }, - { base: "T", letters: "\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786" }, { base: "TZ", letters: "\uA728" }, { base: "U", @@ -91,8 +115,15 @@ const defaultDiacriticsRemovalMap = [ { base: "VY", letters: "\uA760" }, { base: "W", letters: "\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72" }, { base: "X", letters: "\u0058\u24CD\uFF38\u1E8A\u1E8C" }, - { base: "Y", letters: "\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE" }, - { base: "Z", letters: "\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762" }, + { + base: "Y", + letters: + "\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE", + }, + { + base: "Z", + letters: "\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762", + }, { base: "a", letters: @@ -105,8 +136,14 @@ const defaultDiacriticsRemovalMap = [ { base: "av", letters: "\uA739\uA73B" }, { base: "ay", letters: "\uA73D" }, { base: "b", letters: "\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253" }, - { base: "c", letters: "\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184" }, - { base: "d", letters: "\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A" }, + { + base: "c", + letters: "\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184", + }, + { + base: "d", + letters: "\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A", + }, { base: "dz", letters: "\u01F3\u01C6" }, { base: "e", @@ -114,8 +151,16 @@ const defaultDiacriticsRemovalMap = [ "\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD", }, { base: "f", letters: "\u0066\u24D5\uFF46\u1E1F\u0192\uA77C" }, - { base: "g", letters: "\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F" }, - { base: "h", letters: "\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265" }, + { + base: "g", + letters: + "\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F", + }, + { + base: "h", + letters: + "\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265", + }, { base: "hv", letters: "\u0195" }, { base: "i", @@ -123,7 +168,10 @@ const defaultDiacriticsRemovalMap = [ "\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131", }, { base: "j", letters: "\u006A\u24D9\uFF4A\u0135\u01F0\u0249" }, - { base: "k", letters: "\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3" }, + { + base: "k", + letters: "\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3", + }, { base: "l", letters: @@ -133,7 +181,8 @@ const defaultDiacriticsRemovalMap = [ { base: "m", letters: "\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F" }, { base: "n", - letters: "\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5", + letters: + "\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5", }, { base: "nj", letters: "\u01CC" }, { @@ -148,7 +197,8 @@ const defaultDiacriticsRemovalMap = [ { base: "q", letters: "\u0071\u24E0\uFF51\u024B\uA757\uA759" }, { base: "r", - letters: "\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783", + letters: + "\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783", }, { base: "s", @@ -157,7 +207,8 @@ const defaultDiacriticsRemovalMap = [ }, { base: "t", - letters: "\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787", + letters: + "\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787", }, { base: "tz", letters: "\uA729" }, { @@ -171,9 +222,13 @@ const defaultDiacriticsRemovalMap = [ { base: "x", letters: "\u0078\u24E7\uFF58\u1E8B\u1E8D" }, { base: "y", - letters: "\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF", + letters: + "\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF", + }, + { + base: "z", + letters: "\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763", }, - { base: "z", letters: "\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763" }, ] const diacriticsMap: Record = {} diff --git a/src/lib/utils/placeholders.tests.tsx b/src/lib/utils/placeholders.tests.tsx index e2e0fcb7f71..a6d35e7cc62 100644 --- a/src/lib/utils/placeholders.tests.tsx +++ b/src/lib/utils/placeholders.tests.tsx @@ -7,7 +7,9 @@ describe(PlaceholderBox, () => { try { renderWithWrappers() } catch (error: any) { - expect(error.message).toContain("Error: You're using a Placeholder outside of a PlaceholderContext") + expect(error.message).toContain( + "Error: You're using a Placeholder outside of a PlaceholderContext" + ) } renderWithWrappers( diff --git a/src/lib/utils/placeholders.tsx b/src/lib/utils/placeholders.tsx index a6c405b9832..f1729dbfdb3 100644 --- a/src/lib/utils/placeholders.tsx +++ b/src/lib/utils/placeholders.tsx @@ -22,7 +22,11 @@ function useCurrentTime() { } }, []) Animated.useCode( - () => Animated.onChange(isMounted, Animated.cond(isMounted, Animated.startClock(clock), Animated.stopClock(clock))), + () => + Animated.onChange( + isMounted, + Animated.cond(isMounted, Animated.startClock(clock), Animated.stopClock(clock)) + ), [] ) return clock @@ -76,12 +80,12 @@ export const useMemoizedRandom = () => useMemo(Math.random, []) /** * Placeholder with memoized random with between `minWidth` and `maxWidth`. */ -export const RandomWidthPlaceholderText: React.FC = ({ - minWidth, - maxWidth, - ...props -}) => { - return +export const RandomWidthPlaceholderText: React.FC< + ViewStyle & { minWidth: number; maxWidth: number } +> = ({ minWidth, maxWidth, ...props }) => { + return ( + + ) } const BUTTON_HEIGHT = 42 @@ -106,11 +110,11 @@ export class RandomNumberGenerator { } } -export const PlaceholderRaggedText: React.FC<{ numLines: number; seed?: number; textHeight?: number }> = ({ - numLines, - seed = 10, - textHeight = TEXT_HEIGHT, -}) => { +export const PlaceholderRaggedText: React.FC<{ + numLines: number + seed?: number + textHeight?: number +}> = ({ numLines, seed = 10, textHeight = TEXT_HEIGHT }) => { const lengths = useMemo(() => { // create our own little deterministic math.random() to avoid snapshot churn const rng = new RandomNumberGenerator(seed) diff --git a/src/lib/utils/plainTextFromTree.tests.tsx b/src/lib/utils/plainTextFromTree.tests.tsx index bac14de7f15..eb80db71931 100644 --- a/src/lib/utils/plainTextFromTree.tests.tsx +++ b/src/lib/utils/plainTextFromTree.tests.tsx @@ -34,7 +34,8 @@ describe("plainTextFromTree", () => { }) it("correctly handles the output from renderMarkdown", () => { - const markdown = "This is a *link* for an [artist](/artist/andy-warhol) and a [gene](/gene/minimalism)." + const markdown = + "This is a *link* for an [artist](/artist/andy-warhol) and a [gene](/gene/minimalism)." const component = renderMarkdown(markdown) expect(plainTextFromTree(component)).toEqual("This is a link for an artist and a gene.") }) diff --git a/src/lib/utils/queryPrefetching.ts b/src/lib/utils/queryPrefetching.ts index 8e212171ceb..2fe614c8771 100644 --- a/src/lib/utils/queryPrefetching.ts +++ b/src/lib/utils/queryPrefetching.ts @@ -29,7 +29,11 @@ export const useInitializeQueryPrefetching = () => { DEFAULT_QUERIES_PER_INTERVAL ) - limiter = new RateLimiter({ tokensPerInterval: queriesPerInterval, interval: "minute", fireImmediately: true }) + limiter = new RateLimiter({ + tokensPerInterval: queriesPerInterval, + interval: "minute", + fireImmediately: true, + }) }, []) } @@ -40,7 +44,11 @@ const isRateLimited = async () => { return remainingRequests < 0 } -const prefetchQuery = async (environment: Environment, query: GraphQLTaggedNode, variables: Variables = {}) => { +const prefetchQuery = async ( + environment: Environment, + query: GraphQLTaggedNode, + variables: Variables = {} +) => { const operation = createOperationDescriptor(getRequest(query), variables) await fetchQuery(environment, query, variables, { networkCacheConfig: { force: false } }) diff --git a/src/lib/utils/renderMarkdown.tests.tsx b/src/lib/utils/renderMarkdown.tests.tsx index 4ef84fd0c80..f4db9a6a958 100644 --- a/src/lib/utils/renderMarkdown.tests.tsx +++ b/src/lib/utils/renderMarkdown.tests.tsx @@ -18,7 +18,9 @@ describe("renderMarkdown", () => { }) it("returns markdown for multiple paragraphs", () => { - const componentList = renderMarkdown("This is a first paragraph\n\nThis is a second paragraph") as any + const componentList = renderMarkdown( + "This is a first paragraph\n\nThis is a second paragraph" + ) as any expect(componentList.length).toEqual(4) const { queryByText } = renderWithWrappersTL({componentList}) @@ -60,7 +62,10 @@ describe("renderMarkdown", () => { }, }, } - const componentList = renderMarkdown("This is a first paragraph\n\nThis is a second paragraph", customRules) as any + const componentList = renderMarkdown( + "This is a first paragraph\n\nThis is a second paragraph", + customRules + ) as any expect(componentList.length).toEqual(4) const { queryByText } = renderWithWrappersTL({componentList}) expect(queryByText("This is a first paragraph")).toBeTruthy() diff --git a/src/lib/utils/renderMarkdown.tsx b/src/lib/utils/renderMarkdown.tsx index 01fc8c3ebb9..161460f2c71 100644 --- a/src/lib/utils/renderMarkdown.tsx +++ b/src/lib/utils/renderMarkdown.tsx @@ -59,7 +59,11 @@ export function defaultRules({ } return ( - openUrl(node.target)}> + openUrl(node.target)} + > {output(node.content, state)} ) @@ -212,8 +216,11 @@ export function defaultRules({ 3: "subtitle", 4: "text", } - // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 - const size = useNewTextStyles ? newTextMap[node.level] || "subtitle" : map[node.level] || "4" + const size = useNewTextStyles + ? // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + newTextMap[node.level] || "subtitle" + : // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏 + map[node.level] || "4" return useNewTextStyles ? ( {output(node.content, state)} @@ -244,7 +251,13 @@ export function defaultRules({ react: (node, output, state) => ( {({ color, space }) => ( - + {output(node.content, state)} )} @@ -258,7 +271,10 @@ export function defaultRules({ }) } -export function renderMarkdown(markdown: string, rules: any = defaultRules({})): React.ReactElement { +export function renderMarkdown( + markdown: string, + rules: any = defaultRules({}) +): React.ReactElement { const parser = SimpleMarkdown.parserFor(rules) const writer = SimpleMarkdown.outputFor(rules, "react") diff --git a/src/lib/utils/renderWithLoadProgress.tests.tsx b/src/lib/utils/renderWithLoadProgress.tests.tsx index d43fbc36ca7..df3e120a9d5 100644 --- a/src/lib/utils/renderWithLoadProgress.tests.tsx +++ b/src/lib/utils/renderWithLoadProgress.tests.tsx @@ -14,7 +14,10 @@ describe(renderWithLoadProgress, () => { it(`renders the real content when the graphqls are done`, () => { const { getByText } = renderWithWrappersTL( - renderWithLoadProgress(() => the real content, {})({ error: null, props: {}, retry: () => null })! + renderWithLoadProgress( + () => the real content, + {} + )({ error: null, props: {}, retry: () => null })! ) expect(getByText("the real content")).toBeTruthy() diff --git a/src/lib/utils/renderWithPlaceholder.tsx b/src/lib/utils/renderWithPlaceholder.tsx index cf24e5003a5..42aaa6885ca 100644 --- a/src/lib/utils/renderWithPlaceholder.tsx +++ b/src/lib/utils/renderWithPlaceholder.tsx @@ -75,7 +75,11 @@ export function renderWithPlaceholder({ return } } else { - return {renderPlaceholder({ ...placeholderProps })} + return ( + + {renderPlaceholder({ ...placeholderProps })} + + ) } } } diff --git a/src/lib/utils/saleTime.tests.ts b/src/lib/utils/saleTime.tests.ts index b8b053029f6..3767ee1c396 100644 --- a/src/lib/utils/saleTime.tests.ts +++ b/src/lib/utils/saleTime.tests.ts @@ -173,7 +173,12 @@ beforeEach(() => { describe("saleTime", () => { it("returns null when timezone is missing", () => { expect( - saleTime({ startAt: times.present, liveStartAt: times.present, endAt: times.present, timeZone: null }) + saleTime({ + startAt: times.present, + liveStartAt: times.present, + endAt: times.present, + timeZone: null, + }) ).toEqual({ absolute: null, relative: null, @@ -192,7 +197,9 @@ describe("#saleTime.absolute", () => { }) it("recognises whether an auction is over or not", () => { expect(saleTime(finishedSaleNY).absolute).toEqual("Closed on Sep 1") - expect(saleTime(completeNotYetOpenSaleNY).absolute).toEqual("Live bidding begins Sep 5 at 3:00pm EDT") + expect(saleTime(completeNotYetOpenSaleNY).absolute).toEqual( + "Live bidding begins Sep 5 at 3:00pm EDT" + ) expect(saleTime(completeFinishedSaleNY).absolute).toEqual("Closed on Sep 1") }) it("works for currently open sales", () => { diff --git a/src/lib/utils/saleTime.ts b/src/lib/utils/saleTime.ts index 02f27b2aa5c..1ff8ef1ef50 100644 --- a/src/lib/utils/saleTime.ts +++ b/src/lib/utils/saleTime.ts @@ -15,8 +15,11 @@ export const saleTime = (sale: { const saleType = sale.liveStartAt != null ? "live" : "timed" const userTimeZone = moment.tz.guess() const startDateMoment = - startDate !== null ? moment.tz(startDate, moment.ISO_8601, sale.timeZone).tz(userTimeZone) : null - const endDateMoment = endDate !== null ? moment.tz(endDate, moment.ISO_8601, sale.timeZone).tz(userTimeZone) : null + startDate !== null + ? moment.tz(startDate, moment.ISO_8601, sale.timeZone).tz(userTimeZone) + : null + const endDateMoment = + endDate !== null ? moment.tz(endDate, moment.ISO_8601, sale.timeZone).tz(userTimeZone) : null const now = moment() return { @@ -56,7 +59,11 @@ const absolute = ( return null } -const begins = (startDate: moment.Moment, userTimeZone: string, saleType: "live" | "timed"): string => +const begins = ( + startDate: moment.Moment, + userTimeZone: string, + saleType: "live" | "timed" +): string => `${saleType === "live" ? "Live bidding" : "Bidding"} ` + `begins ${startDate.format("MMM D")} ` + `at ${startDate.format("h:mma")} ` + @@ -97,7 +104,9 @@ const relative = ( const maybePluralise = (word: string, unit: number) => word + (unit === 1 ? "" : "s") const maybeAddMinutes = (minutesUntilSale: number) => - minutesUntilSale % 60 === 0 ? "" : ` ${minutesUntilSale % 60} ${maybePluralise("minute", minutesUntilSale)}` + minutesUntilSale % 60 === 0 + ? "" + : ` ${minutesUntilSale % 60} ${maybePluralise("minute", minutesUntilSale)}` const starts = (now: moment.Moment, startDate: moment.Moment): string | null => { const hours = startDate.diff(now, "hours") diff --git a/src/lib/utils/sendEmail.tests.ts b/src/lib/utils/sendEmail.tests.ts index 8e2751e860e..a6b79470f96 100644 --- a/src/lib/utils/sendEmail.tests.ts +++ b/src/lib/utils/sendEmail.tests.ts @@ -42,13 +42,18 @@ describe("sendEmail", () => { it("calls Linking.openURL with the correct argument", async () => { await sendEmail("specialist@artsy.net", { subject: "Greetings" }) expect(Linking.openURL).toHaveBeenCalledTimes(1) - expect(Linking.openURL).toHaveBeenCalledWith("mailto:specialist@artsy.net?subject=Greetings") + expect(Linking.openURL).toHaveBeenCalledWith( + "mailto:specialist@artsy.net?subject=Greetings" + ) }) }) describe("when there is an email address with a subject line and a ", () => { it("calls Linking.openURL with the correct argument", async () => { - await sendEmail("specialist@artsy.net", { subject: "Greetings", body: "Hello, I need help." }) + await sendEmail("specialist@artsy.net", { + subject: "Greetings", + body: "Hello, I need help.", + }) expect(Linking.openURL).toHaveBeenCalledTimes(1) expect(Linking.openURL).toHaveBeenCalledWith( "mailto:specialist@artsy.net?subject=Greetings&body=Hello, I need help." diff --git a/src/lib/utils/track/SegmentTrackingProvider.ts b/src/lib/utils/track/SegmentTrackingProvider.ts index 4a59f45e989..22402af83f4 100644 --- a/src/lib/utils/track/SegmentTrackingProvider.ts +++ b/src/lib/utils/track/SegmentTrackingProvider.ts @@ -19,8 +19,12 @@ export const SegmentTrackingProvider: TrackingProvider = { analytics .setup( Platform.select({ - ios: __DEV__ ? Config.SEGMENT_STAGING_WRITE_KEY_IOS : Config.SEGMENT_PRODUCTION_WRITE_KEY_IOS, - android: __DEV__ ? Config.SEGMENT_STAGING_WRITE_KEY_ANDROID : Config.SEGMENT_PRODUCTION_WRITE_KEY_ANDROID, + ios: __DEV__ + ? Config.SEGMENT_STAGING_WRITE_KEY_IOS + : Config.SEGMENT_PRODUCTION_WRITE_KEY_IOS, + android: __DEV__ + ? Config.SEGMENT_STAGING_WRITE_KEY_ANDROID + : Config.SEGMENT_PRODUCTION_WRITE_KEY_ANDROID, default: "", }), { diff --git a/src/lib/utils/track/index.tsx b/src/lib/utils/track/index.tsx index e42de2bf3dd..0ed2b2dc1eb 100644 --- a/src/lib/utils/track/index.tsx +++ b/src/lib/utils/track/index.tsx @@ -56,7 +56,8 @@ export { Schema } * * ``` */ -export interface Track

extends _Track {} // tslint:disable-line:no-empty-interface +export interface Track

+ extends _Track {} // tslint:disable-line:no-empty-interface /** * A typed tracking-info alias of the default react-tracking `track` function. diff --git a/src/lib/utils/track/providers.tsx b/src/lib/utils/track/providers.tsx index e9e26f31a16..652aa94e862 100644 --- a/src/lib/utils/track/providers.tsx +++ b/src/lib/utils/track/providers.tsx @@ -14,7 +14,8 @@ type NativeIOSTrackingEventID = } | { event_name: string } -export const isCohesionScreen = (info: CohesionAction | Screen): info is Screen => info.action === ActionType.screen +export const isCohesionScreen = (info: CohesionAction | Screen): info is Screen => + info.action === ActionType.screen interface LegacyNameAction { // TODO: This can be removed once we remove these uses. Currently there is one in `WorksForYou` and one in `ArtistRail`. diff --git a/src/lib/utils/track/tracking.tests.tsx b/src/lib/utils/track/tracking.tests.tsx index 41d7f4a61fc..8464a31f0ca 100644 --- a/src/lib/utils/track/tracking.tests.tsx +++ b/src/lib/utils/track/tracking.tests.tsx @@ -37,7 +37,10 @@ describe("Tracking", () => { const button = component.findByType(Button) button.props.onPress() expect(postEventToProviders).toHaveBeenCalledTimes(2) - expect(postEventToProviders).toHaveBeenNthCalledWith(2, { aScreen: "a test screen", wow: "yes!" }) + expect(postEventToProviders).toHaveBeenNthCalledWith(2, { + aScreen: "a test screen", + wow: "yes!", + }) }) @screenTrack({ aScreen: "a class screen" } as any) @@ -67,6 +70,9 @@ describe("Tracking", () => { const button = component.findByType(Button) button.props.onPress() expect(postEventToProviders).toHaveBeenCalledTimes(2) - expect(postEventToProviders).toHaveBeenNthCalledWith(2, { aScreen: "a class screen", wow: "indeed!" }) + expect(postEventToProviders).toHaveBeenNthCalledWith(2, { + aScreen: "a class screen", + wow: "indeed!", + }) }) }) diff --git a/src/lib/utils/useAlgoliaIndices.ts b/src/lib/utils/useAlgoliaIndices.ts index 550bb22ce99..0d3798a8714 100644 --- a/src/lib/utils/useAlgoliaIndices.ts +++ b/src/lib/utils/useAlgoliaIndices.ts @@ -10,7 +10,10 @@ interface IndicesInfo { [key: string]: IndexInfo } -export const useAlgoliaIndices = (client: SearchClient | null, indices?: ReadonlyArray<{ name: string }>) => { +export const useAlgoliaIndices = ( + client: SearchClient | null, + indices?: ReadonlyArray<{ name: string }> +) => { const [indicesInfo, setIndicesInfo] = useState({}) const [loading, setLoading] = useState(false) const lastQuery = useRef(null) @@ -33,12 +36,15 @@ export const useAlgoliaIndices = (client: SearchClient | null, indices?: Readonl setLoading(true) const indicesResponse = await client.multipleQueries(queries) if (query === lastQuery.current) { - const newIndicesInfo = indicesResponse.results.reduce((acc: IndicesInfo, { index, nbHits }) => { - if (!!index) { - acc[index] = { hasResults: !!nbHits } - } - return acc - }, {}) + const newIndicesInfo = indicesResponse.results.reduce( + (acc: IndicesInfo, { index, nbHits }) => { + if (!!index) { + acc[index] = { hasResults: !!nbHits } + } + return acc + }, + {} + ) setIndicesInfo(newIndicesInfo) setLoading(false) } diff --git a/src/lib/utils/useAppState.tsx b/src/lib/utils/useAppState.tsx index b6e7a403022..38658bbac58 100644 --- a/src/lib/utils/useAppState.tsx +++ b/src/lib/utils/useAppState.tsx @@ -19,7 +19,11 @@ export default function useAppState({ onForeground, onBackground }: AppStateProp useEffect(() => { const _handleAppStateChange = (nextAppState: AppStateStatus) => { // App has come to the foreground - if (appState.current.match(/inactive|background/) && nextAppState === "active" && onForeground) { + if ( + appState.current.match(/inactive|background/) && + nextAppState === "active" && + onForeground + ) { onForeground() } diff --git a/src/lib/utils/useEventTiming.tsx b/src/lib/utils/useEventTiming.tsx index f7010d1dea3..9280b4d2f88 100644 --- a/src/lib/utils/useEventTiming.tsx +++ b/src/lib/utils/useEventTiming.tsx @@ -19,13 +19,16 @@ export const useEventTiming = ({ startAt = DateTime.local().toString(), endAt = DateTime.local().toString(), }: UseEventTiming) => { - const durationTilEnd = Duration.fromISO(DateTime.fromISO(endAt).diff(DateTime.fromISO(currentTime)).toString()) + const durationTilEnd = Duration.fromISO( + DateTime.fromISO(endAt).diff(DateTime.fromISO(currentTime)).toString() + ) const daysTilEnd = durationTilEnd.as("days") const hoursTillEnd = durationTilEnd.as("hours") const secondsTilEnd = durationTilEnd.as("seconds") const hasStarted = - Duration.fromISO(DateTime.fromISO(startAt).diff(DateTime.fromISO(currentTime)).toString()).seconds < 0 + Duration.fromISO(DateTime.fromISO(startAt).diff(DateTime.fromISO(currentTime)).toString()) + .seconds < 0 const hasEnded = Math.floor(secondsTilEnd) <= 0 const closesSoon = daysTilEnd <= 3 && daysTilEnd >= 1 diff --git a/src/lib/utils/useExperiments.ts b/src/lib/utils/useExperiments.ts index 0a11348a5e8..4a7d489af5b 100644 --- a/src/lib/utils/useExperiments.ts +++ b/src/lib/utils/useExperiments.ts @@ -12,14 +12,18 @@ let client: SplitIO.IClient | null = null export const useExperiments = () => { const enableSplitIOABTesting = useFeatureFlag("AREnableSplitIOABTesting") const environment = GlobalStore.useAppState((store) => store.config.environment.env) - const userIdOrDeviceId = GlobalStore.useAppState((store) => store.auth.userID ?? `not-logged-in_${getUniqueId()}`) + const userIdOrDeviceId = GlobalStore.useAppState( + (store) => store.auth.userID ?? `not-logged-in_${getUniqueId()}` + ) useEffect(() => { if (enableSplitIOABTesting) { const config: IReactNativeSettings = { core: { authorizationKey: - environment === "staging" ? Config.SPLIT_IO_STAGING_API_KEY : Config.SPLIT_IO_PRODUCTION_API_KEY, + environment === "staging" + ? Config.SPLIT_IO_STAGING_API_KEY + : Config.SPLIT_IO_PRODUCTION_API_KEY, key: userIdOrDeviceId, }, streamingEnabled: true, @@ -28,13 +32,18 @@ export const useExperiments = () => { client = client ?? factory.client() client?.on(client.Event.SDK_READY, () => { - GlobalStore.actions.config.experiments.setSessionState({ isReady: true, lastUpdate: DateTime.utc().toISO() }) + GlobalStore.actions.config.experiments.setSessionState({ + isReady: true, + lastUpdate: DateTime.utc().toISO(), + }) }) client?.on(client.Event.SDK_READY_TIMED_OUT, () => { GlobalStore.actions.config.experiments.setSessionState({ isReady: false }) }) client?.on(client.Event.SDK_UPDATE, () => { - GlobalStore.actions.config.experiments.setSessionState({ lastUpdate: DateTime.now().toISO() }) + GlobalStore.actions.config.experiments.setSessionState({ + lastUpdate: DateTime.now().toISO(), + }) }) } }, [enableSplitIOABTesting]) @@ -50,7 +59,9 @@ export const useTreatment = (treatment: EXPERIMENT_NAME) => { // That means that when `client.getTreatment(treatment)` runs, it will return a new value. // So we "read" this value, in order to make the hook re-render the components it is used in. // @ts-ignore - const _lastUpdate = GlobalStore.useAppState((store) => store.config.experiments.sessionState.lastUpdate) + const _lastUpdate = GlobalStore.useAppState( + (store) => store.config.experiments.sessionState.lastUpdate + ) if (!enableSplitIOABTesting) { return experiments[treatment].fallbackTreatment diff --git a/src/lib/utils/useImageSearch.tsx b/src/lib/utils/useImageSearch.tsx index 729fd7252bc..ded6f0a6bf6 100644 --- a/src/lib/utils/useImageSearch.tsx +++ b/src/lib/utils/useImageSearch.tsx @@ -17,7 +17,10 @@ export const useImageSearch = () => { const convectionKey = await getConvectionGeminiKey() const acl = "private" - const assetCredentials = await getGeminiCredentialsForEnvironment({ acl, name: convectionKey || "" }) + const assetCredentials = await getGeminiCredentialsForEnvironment({ + acl, + name: convectionKey || "", + }) const s3 = await uploadFileToS3(imgPath, acl, assetCredentials) return `https://artsy-hack9.imgix.net/${s3.key}?trim=auto&trim-sd=25&q=1` @@ -62,9 +65,12 @@ export const useImageSearch = () => { const imgUrl = await getImgixUrl(image?.path!) const response = await reverseImageSearch(imgUrl) if (isEmpty(response.result)) { - setErrorMessage("Unfortunatelly we didn't find anything for this image. Please try another one.") + setErrorMessage( + "Unfortunatelly we didn't find anything for this image. Please try another one." + ) } - const artworkHref = response.result[0]?.metadata?.artworkHref ?? response.result[0]?.metadata?.href + const artworkHref = + response.result[0]?.metadata?.artworkHref ?? response.result[0]?.metadata?.href if (!!artworkHref) { // close modal setIsModalVisible(false) diff --git a/src/lib/utils/useInitialNotification.ts b/src/lib/utils/useInitialNotification.ts index 7beff1f1d13..b577bbe5982 100644 --- a/src/lib/utils/useInitialNotification.ts +++ b/src/lib/utils/useInitialNotification.ts @@ -8,7 +8,9 @@ export function useInitialNotification() { const isLoggedIn = GlobalStore.useAppState((state) => !!state.auth.userAccessToken) - const pendingNotification = GlobalStore.useAppState((state) => state.pendingPushNotification.notification) + const pendingNotification = GlobalStore.useAppState( + (state) => state.pendingPushNotification.notification + ) useEffect(() => { if (isLoggedIn && !hasHandledInitialNotification) { diff --git a/src/lib/utils/usePreferredThemeTracking.tests.ts b/src/lib/utils/usePreferredThemeTracking.tests.ts index 89e87af01e9..1acb843826d 100644 --- a/src/lib/utils/usePreferredThemeTracking.tests.ts +++ b/src/lib/utils/usePreferredThemeTracking.tests.ts @@ -7,6 +7,8 @@ describe("usePreferredThemeTracking", () => { renderHook(() => usePreferredThemeTracking()) expect(SegmentTrackingProvider.identify).toHaveBeenCalledTimes(1) - expect(SegmentTrackingProvider.identify).toHaveBeenCalledWith(null, { "user interface style": "light" }) + expect(SegmentTrackingProvider.identify).toHaveBeenCalledWith(null, { + "user interface style": "light", + }) }) }) diff --git a/src/lib/utils/useScreenReaderTracking.tests.ts b/src/lib/utils/useScreenReaderTracking.tests.ts index 3a15e46209a..7663dac6930 100644 --- a/src/lib/utils/useScreenReaderTracking.tests.ts +++ b/src/lib/utils/useScreenReaderTracking.tests.ts @@ -15,7 +15,9 @@ describe("useScreenReaderTracking", () => { await act(() => waitFor(() => { expect(SegmentTrackingProvider.identify).toHaveBeenCalledTimes(1) - expect(SegmentTrackingProvider.identify).toHaveBeenCalledWith(null, { "screen reader status": "enabled" }) + expect(SegmentTrackingProvider.identify).toHaveBeenCalledWith(null, { + "screen reader status": "enabled", + }) }) ) }) diff --git a/src/lib/utils/useStickyScrollHeader.tsx b/src/lib/utils/useStickyScrollHeader.tsx index ffb68a1282b..7898c92e7b2 100644 --- a/src/lib/utils/useStickyScrollHeader.tsx +++ b/src/lib/utils/useStickyScrollHeader.tsx @@ -46,7 +46,9 @@ export const useStickyScrollHeader = ({ () => ( ) => React.ReactNode) }) => { const hookStuff = useTheme() - return {typeof children === "function" ? children(hookStuff) : children} + return ( + {typeof children === "function" ? children(hookStuff) : children} + ) } diff --git a/src/palette/Theme.tsx b/src/palette/Theme.tsx index 3c9a0552d19..90c4ab013c0 100644 --- a/src/palette/Theme.tsx +++ b/src/palette/Theme.tsx @@ -143,7 +143,10 @@ const THEMES = { semibold: { normal: null, italic: null }, }, serif: { - regular: { normal: "ReactNativeAGaramondPro-Regular", italic: "ReactNativeAGaramondPro-Italic" }, + regular: { + normal: "ReactNativeAGaramondPro-Regular", + italic: "ReactNativeAGaramondPro-Italic", + }, medium: { normal: null, italic: null }, semibold: { normal: "ReactNativeAGaramondPro-Semibold", italic: null }, }, @@ -233,7 +236,9 @@ export const useTheme = () => { console.error( "You are trying to use the `Theme` but you have not wrapped your component/screen with ``. Please wrap and try again." ) - throw new Error("ThemeContext is not defined. Wrap your component with `` and try again.") + throw new Error( + "ThemeContext is not defined. Wrap your component with `` and try again." + ) } const themeIfUnwrapped = THEMES.v3 diff --git a/src/palette/elements/Avatar/Avatar.tests.tsx b/src/palette/elements/Avatar/Avatar.tests.tsx index 5f738872eee..973b1d0b063 100644 --- a/src/palette/elements/Avatar/Avatar.tests.tsx +++ b/src/palette/elements/Avatar/Avatar.tests.tsx @@ -21,7 +21,9 @@ describe("Avatar", () => { it("returns correct sizes with initials", () => { const getInitialHolder = (size: any) => - renderWithWrappersTL().container.findByType(InitialsHolder) + renderWithWrappersTL().container.findByType( + InitialsHolder + ) expect(getInitialHolder("xxs").props.width).toEqual(30) expect(getInitialHolder("xs").props.height).toEqual(45) diff --git a/src/palette/elements/Banner/Banner.tests.tsx b/src/palette/elements/Banner/Banner.tests.tsx index de4555ac9e3..8b7918cf3d8 100644 --- a/src/palette/elements/Banner/Banner.tests.tsx +++ b/src/palette/elements/Banner/Banner.tests.tsx @@ -21,13 +21,17 @@ describe("Banner", () => { }) it("shows close button when showCloseButton", () => { - const { getByTestId } = renderWithWrappersTL() + const { getByTestId } = renderWithWrappersTL( + + ) expect(getByTestId("banner-close-button")).toBeDefined() }) it("fires onClose press event", () => { const onClose = jest.fn() - const { getByTestId } = renderWithWrappersTL() + const { getByTestId } = renderWithWrappersTL( + + ) fireEvent.press(getByTestId("banner-close-button")) expect(onClose).toHaveBeenCalled() }) diff --git a/src/palette/elements/Banner/Banner.tsx b/src/palette/elements/Banner/Banner.tsx index 51c95e44444..05590d553c9 100644 --- a/src/palette/elements/Banner/Banner.tsx +++ b/src/palette/elements/Banner/Banner.tsx @@ -73,7 +73,10 @@ export const Banner: React.FC = ({ onPress={handleClose} hitSlop={{ bottom: 40, right: 40, left: 40, top: 40 }} > - + )} diff --git a/src/palette/elements/Box/Box.tsx b/src/palette/elements/Box/Box.tsx index 26215b99fd2..afd58e0463d 100644 --- a/src/palette/elements/Box/Box.tsx +++ b/src/palette/elements/Box/Box.tsx @@ -34,7 +34,16 @@ export interface BoxProps /** * All the system functions for Box */ -export const boxMixin = compose(background, border, color, flexbox, layout, position, space, textAlign) +export const boxMixin = compose( + background, + border, + color, + flexbox, + layout, + position, + space, + textAlign +) /** * Box is just a `View` with common styled-system props. diff --git a/src/palette/elements/Button/Button.stories.tsx b/src/palette/elements/Button/Button.stories.tsx index 54a5f057868..09deff235d7 100644 --- a/src/palette/elements/Button/Button.stories.tsx +++ b/src/palette/elements/Button/Button.stories.tsx @@ -46,7 +46,11 @@ storiesOf("Button", module) ( - )} @@ -111,7 +115,13 @@ storiesOf("Button", module) loading and disabled - + @@ -122,7 +132,11 @@ storiesOf("Button", module) - diff --git a/src/palette/elements/Button/Button.tsx b/src/palette/elements/Button/Button.tsx index 3e5ebcb3aa6..c7135db383d 100644 --- a/src/palette/elements/Button/Button.tsx +++ b/src/palette/elements/Button/Button.tsx @@ -18,7 +18,14 @@ export interface ButtonProps extends BoxProps { children: ReactNode size?: "small" | "large" - variant?: "fillDark" | "fillLight" | "fillGray" | "outline" | "outlineGray" | "outlineLight" | "text" + variant?: + | "fillDark" + | "fillLight" + | "fillGray" + | "outline" + | "outlineGray" + | "outlineLight" + | "text" onPress?: PressableProps["onPress"] icon?: ReactNode @@ -76,7 +83,10 @@ export const Button: React.FC = ({ const [innerDisplayState, setInnerDisplayState] = useState(DisplayState.Enabled) - const [longestTextMeasurements, setLongestTextMeasurements] = useState({ width: 0, height: 0 }) + const [longestTextMeasurements, setLongestTextMeasurements] = useState({ + width: 0, + height: 0, + }) const displayState = testOnly_state ?? // if we use the test prop, use that diff --git a/src/palette/elements/Button/CTAButton.tsx b/src/palette/elements/Button/CTAButton.tsx index cb2059f096f..6244fcfc2a0 100644 --- a/src/palette/elements/Button/CTAButton.tsx +++ b/src/palette/elements/Button/CTAButton.tsx @@ -2,4 +2,6 @@ import { Button } from "palette" import { ButtonProps } from "palette" import React from "react" -export const CTAButton: React.FC = (props) =>