Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[wip] fix: Update tasks list using the relay store #11247

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/app/Components/Tasks/Task.tests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ const mockDissmissTask = jest.fn()
const mockAcknowledgeTask = jest.fn()

jest.mock("app/utils/mutations/useDismissTask", () => ({
useDismissTask: () => ({ submitMutation: mockDissmissTask }),
useDismissTask: () => [mockDissmissTask],
}))

jest.mock("app/utils/mutations/useAcknowledgeTask.ts", () => ({
useAcknowledgeTask: () => ({ submitMutation: mockAcknowledgeTask }),
useAcknowledgeTask: () => [mockAcknowledgeTask],
}))

describe("Task Component", () => {
Expand Down
53 changes: 41 additions & 12 deletions src/app/Components/Tasks/Task.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ContextModule } from "@artsy/cohesion"
import { Flex, Image, Text, Touchable } from "@artsy/palette-mobile"
import { captureMessage } from "@sentry/react-native"
import { Task_task$key } from "__generated__/Task_task.graphql"
import { Swipeable } from "app/Components/Swipeable/Swipeable"
import { useHomeViewTracking } from "app/Scenes/HomeView/hooks/useHomeViewTracking"
Expand All @@ -15,37 +16,64 @@ const TASK_IMAGE_SIZE = 60

interface TaskProps {
disableSwipeable?: boolean
onClearTask: () => void
onClearTask?: () => void
onPress?: () => void
task: Task_task$key
}

export const Task = forwardRef<SwipeableMethods, TaskProps>(
({ disableSwipeable, onClearTask, onPress, ...restProps }, ref) => {
const task = useFragment(taskFragment, restProps.task)
const { tappedTaskGroup, tappedClearTask } = useHomeViewTracking()
const { submitMutation: dismissTask } = useDismissTask()
const { submitMutation: acknowledgeTask } = useAcknowledgeTask()
const [dismissTask, dismissInProgress] = useDismissTask(task.id)
const [acknowledgeTask, acknowledgeInProgress] = useAcknowledgeTask(task.id)
const fontScale = PixelRatio.getFontScale()

const task = useFragment(taskFragment, restProps.task)

const handlePressTask = async () => {
const handlePressTask = () => {
if (onPress) {
onPress()
return
}

await acknowledgeTask({ variables: { taskID: task.internalID } })
if (acknowledgeInProgress) {
return
}

acknowledgeTask({
variables: { taskID: task.internalID },
onError: (error) => {
if (__DEV__) {
console.error("[useAcknowledgeTaskMutation] Error: ", error.message)
} else {
captureMessage(`useAcknowledgeTaskMutation ${error.message}`)
}
},
})

tappedTaskGroup(ContextModule.actNow, task.actionLink, task.internalID, task.taskType)
onClearTask()
onClearTask?.()

navigate(task.actionLink)
}

const handleClearTask = async () => {
await dismissTask({ variables: { taskID: task.internalID } })
const handleClearTask = () => {
if (dismissInProgress) {
return
}

dismissTask({
variables: { taskID: task.internalID },
onError: (error) => {
if (__DEV__) {
console.error("[useDismissTaskMutation] Error: ", error.message)
} else {
captureMessage(`useDismissTaskMutation ${error.message}`)
}
},
})

tappedClearTask(ContextModule.actNow, task.actionLink, task.internalID, task.taskType)
onClearTask()
onClearTask?.()
}

return (
Expand All @@ -62,7 +90,7 @@ export const Task = forwardRef<SwipeableMethods, TaskProps>(
enabled={!disableSwipeable}
>
<Flex backgroundColor="white100" borderRadius={5}>
<Touchable onPress={handlePressTask}>
<Touchable onPress={handlePressTask} disabled={dismissInProgress}>
<Flex
p={1}
ml={2}
Expand Down Expand Up @@ -96,6 +124,7 @@ export const Task = forwardRef<SwipeableMethods, TaskProps>(

const taskFragment = graphql`
fragment Task_task on Task {
id
actionLink
imageUrl
internalID
Expand Down
31 changes: 10 additions & 21 deletions src/app/Scenes/HomeView/Sections/HomeViewSectionTasks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const MAX_NUMBER_OF_TASKS = 10
// Height of each task + seperator
const TASK_CARD_HEIGHT = 92

type Task = ExtractNodeType<HomeViewSectionTasks_section$data["tasksConnection"]>
type Task = ExtractNodeType<HomeViewSectionTasks_section$data["tasks"]>

interface HomeViewSectionTasksProps extends FlexProps {
section: HomeViewSectionTasks_section$key
Expand All @@ -52,17 +52,15 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
}) => {
const swipeableRef = useRef<SwipeableMethods>(null)
const section = useFragment(tasksFragment, sectionProp)
const tasks = extractNodes(section.tasksConnection)
const tasks = extractNodes(section.tasks)
const isFocused = useIsFocused()

const { isDismissed } = GlobalStore.useAppState((state) => state.progressiveOnboarding)
const { dismiss } = GlobalStore.actions.progressiveOnboarding

const [clearedTasks, setClearedTasks] = useState<string[]>([])
const [showAll, setShowAll] = useState(false)

const filteredTasks = tasks.filter((task) => !clearedTasks.includes(task.internalID))
const displayTaskStack = filteredTasks.length > 1 && !showAll
const displayTaskStack = tasks.length > 1 && !showAll
const HeaderIconComponent = showAll ? ArrowUpIcon : ArrowDownIcon

const task = tasks?.[0]
Expand Down Expand Up @@ -92,14 +90,6 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
}
}, [shouldStartOnboardingAnimation])

const handleClearTask = (task: Task) => {
if (!task) {
return
}

setClearedTasks((prev) => [...prev, task.internalID])
}

const renderCell = useCallback(({ index, ...rest }: CellRendererProps<Task>) => {
return <Box zIndex={-index} {...rest} />
}, [])
Expand Down Expand Up @@ -128,7 +118,6 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
>
<Task
disableSwipeable={displayTaskStack}
onClearTask={() => handleClearTask(item)}
onPress={displayTaskStack ? () => setShowAll((prev) => !prev) : undefined}
ref={swipeableRef}
task={item}
Expand All @@ -137,7 +126,7 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
</Flex>
)
},
[displayTaskStack, handleClearTask, showAll]
[displayTaskStack, showAll]
)

const motiViewHeight = useMemo(() => {
Expand All @@ -148,12 +137,12 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
return singleTaskHeight
}

return singleTaskHeight + (filteredTasks.length - 1) * TASK_CARD_HEIGHT
}, [filteredTasks, showAll])
return singleTaskHeight + (tasks.length - 1) * TASK_CARD_HEIGHT
}, [tasks, showAll])

return (
<AnimatePresence>
{!!filteredTasks.length && (
{!!tasks.length && (
<MotiView
transition={{ type: "timing" }}
animate={{ opacity: 1, height: motiViewHeight }}
Expand All @@ -165,7 +154,7 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
<SectionTitle
title={section.component?.title}
RightButtonContent={() => {
if (filteredTasks.length < 2) {
if (tasks.length < 2) {
return null
}

Expand All @@ -183,7 +172,7 @@ export const HomeViewSectionTasks: React.FC<HomeViewSectionTasksProps> = ({
<Flex mr={2}>
<FlatList
scrollEnabled={false}
data={filteredTasks}
data={tasks}
keyExtractor={(item) => item.internalID}
CellRendererComponent={renderCell}
ItemSeparatorComponent={() => <Spacer y={1} />}
Expand Down Expand Up @@ -211,7 +200,7 @@ const tasksFragment = graphql`
component {
title
}
tasksConnection(first: $numberOfTasks) {
tasks: tasksConnection(first: $numberOfTasks) @connection(key: "HomeViewSectionTasks_tasks") {
edges {
node {
internalID
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe("HomeViewSectionTasks", () => {
component: {
title: "Act Now",
},
tasksConnection: mockTasks,
tasks: mockTasks,
}),
})

Expand All @@ -64,7 +64,7 @@ describe("HomeViewSectionTasks", () => {
component: {
title: "Act Now",
},
tasksConnection: {
tasks: {
edges: [
{
node: {
Expand Down Expand Up @@ -94,7 +94,7 @@ describe("HomeViewSectionTasks", () => {
component: {
title: "Act Now",
},
tasksConnection: mockTasks,
tasks: mockTasks,
}),
})

Expand Down Expand Up @@ -129,7 +129,7 @@ describe("HomeViewSectionTasks", () => {
component: {
title: "Act Now",
},
tasksConnection: mockTasks,
tasks: mockTasks,
}),
})

Expand Down
47 changes: 41 additions & 6 deletions src/app/utils/mutations/useAcknowledgeTask.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,46 @@
import { useAcknowledgeTaskMutation } from "__generated__/useAcknowledgeTaskMutation.graphql"
import { useMutation } from "app/utils/useMutation"
import { graphql } from "react-relay"
import { ConnectionHandler, graphql, useMutation, UseMutationConfig } from "react-relay"

export const useAcknowledgeTask = () => {
return useMutation<useAcknowledgeTaskMutation>({
mutation: AcknowledgeTaskMutation,
})
type MutationConfig = UseMutationConfig<useAcknowledgeTaskMutation>
type MutationResult = [(config: MutationConfig) => void, boolean]

export const useAcknowledgeTask = (taskID: string): MutationResult => {
const [initialCommit, isInProgress] =
useMutation<useAcknowledgeTaskMutation>(AcknowledgeTaskMutation)

const commit = (config: MutationConfig) => {
return initialCommit({
...config,
updater: (store, data) => {
const response = data.ackTask?.taskOrError
const homeViewTaskSection = store
.getRoot()
.getLinkedRecord("homeView")
?.getLinkedRecord("section", { id: "home-view-section-tasks" })

if (!homeViewTaskSection || !response) {
return
}

const task = store.get(taskID)
const key = "HomeViewSectionTasks_tasks"
const tasksConnection = ConnectionHandler.getConnection(homeViewTaskSection, key)
const mutationPayload = store.getRootField("ackTask")
const taskOrError = mutationPayload?.getLinkedRecord("taskOrError")
const taskAcknowledged = taskOrError?.getLinkedRecord("task")

if (!tasksConnection || !task || !taskAcknowledged) {
return
}

if (!!taskAcknowledged) {
ConnectionHandler.deleteNode(tasksConnection, taskID)
}
Comment on lines +36 to +38
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non-blocking: If it is possible to include the fragment that gets the list of tasks in your mutation gql fields, then the relevant store data will be updated without needing to get surgical (you could still use an optimistic update to temporarily remove that task). I think this would be something like here - ...HomeViewSectionTasks_section so maybe not easy to access from this mutation.

Copy link
Member

@damassi damassi Dec 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was just gonna post the same thing @erikdstock! Can this be rolled up in the mutation query itself, in one quick fragment spread in the response?

(these days its rare to have to mutate the store manually)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code looks quite complex and hard to understand, and it seems like it could break very easily, which would break the entire dismiss logic in the component.

I would vote for either keeping it simple (like the initial not-100%-ideal solution with useState) or trying to make it work with a fragment spread.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with this being not easy to ready, I'll try spreading the fragment in the query and see what happens :)

},
})
}

return [commit, isInProgress]
}

const AcknowledgeTaskMutation = graphql`
Expand Down
46 changes: 40 additions & 6 deletions src/app/utils/mutations/useDismissTask.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,45 @@
import { useDismissTaskMutation } from "__generated__/useDismissTaskMutation.graphql"
import { useMutation } from "app/utils/useMutation"
import { graphql } from "react-relay"
import { ConnectionHandler, graphql, useMutation, UseMutationConfig } from "react-relay"

export const useDismissTask = () => {
return useMutation<useDismissTaskMutation>({
mutation: DismissTaskMutation,
})
type MutationConfig = UseMutationConfig<useDismissTaskMutation>
type MutationResult = [(config: MutationConfig) => void, boolean]

export const useDismissTask = (taskID: string): MutationResult => {
const [initialCommit, isInProgress] = useMutation<useDismissTaskMutation>(DismissTaskMutation)

const commit = (config: MutationConfig) => {
return initialCommit({
...config,
updater: (store, data) => {
const response = data.dismissTask?.taskOrError
const homeViewTaskSection = store
.getRoot()
.getLinkedRecord("homeView")
?.getLinkedRecord("section", { id: "home-view-section-tasks" })

if (!homeViewTaskSection || !response) {
return
}

const task = store.get(taskID)
const key = "HomeViewSectionTasks_tasks"
const tasksConnection = ConnectionHandler.getConnection(homeViewTaskSection, key)
const mutationPayload = store.getRootField("dismissTask")
const taskOrError = mutationPayload?.getLinkedRecord("taskOrError")
const taskDismissed = taskOrError?.getLinkedRecord("task")

if (!tasksConnection || !task || !taskDismissed) {
return
}

if (!!taskDismissed) {
ConnectionHandler.deleteNode(tasksConnection, taskID)
}
},
})
}

return [commit, isInProgress]
}

const DismissTaskMutation = graphql`
Expand Down