|
| 1 | +/* |
| 2 | + * This program is free software: you can redistribute it and/or modify it under |
| 3 | + * the terms of the GNU General Public License as published by the Free Software |
| 4 | + * Foundation, either version 3 of the License, or (at your option) any later |
| 5 | + * version. |
| 6 | + * |
| 7 | + * This program is distributed in the hope that it will be useful, but WITHOUT |
| 8 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 9 | + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
| 10 | + * details. |
| 11 | + * |
| 12 | + * You should have received a copy of the GNU General Public License along with |
| 13 | + * this program. If not, see <https://www.gnu.org/licenses/>. |
| 14 | + */ |
| 15 | + |
| 16 | +import { useDevice } from "@/components/providers/device-provider" |
| 17 | +import { useMutation, useQueryClient } from "@tanstack/react-query" |
| 18 | +import { produce } from "immer" |
| 19 | + |
| 20 | +type SetGamepadButtonsParams = { |
| 21 | + start: number |
| 22 | + buttons: number[] |
| 23 | +} |
| 24 | + |
| 25 | +export function useSetGamepadButtons(profile: number) { |
| 26 | + const { id, setGamepadButtons } = useDevice() |
| 27 | + |
| 28 | + const queryClient = useQueryClient() |
| 29 | + const queryKey = [id, profile, "gamepadButtons"] |
| 30 | + |
| 31 | + return useMutation({ |
| 32 | + mutationFn: ({ start, buttons }: SetGamepadButtonsParams) => |
| 33 | + setGamepadButtons(profile, start, buttons), |
| 34 | + onMutate: async ({ start, buttons }) => { |
| 35 | + await queryClient.cancelQueries({ queryKey }) |
| 36 | + const previousButtons = queryClient.getQueryData<number[]>(queryKey) |
| 37 | + queryClient.setQueryData( |
| 38 | + queryKey, |
| 39 | + produce(previousButtons, (draft) => { |
| 40 | + if (draft) { |
| 41 | + for (let i = 0; i < buttons.length; i++) { |
| 42 | + draft[start + i] = buttons[i] |
| 43 | + } |
| 44 | + } |
| 45 | + }), |
| 46 | + ) |
| 47 | + |
| 48 | + return { previousButtons } |
| 49 | + }, |
| 50 | + onError: (err, _, context) => { |
| 51 | + console.error(err) |
| 52 | + queryClient.setQueryData(queryKey, context?.previousButtons) |
| 53 | + }, |
| 54 | + onSettled: () => queryClient.invalidateQueries({ queryKey }), |
| 55 | + }) |
| 56 | +} |
0 commit comments