2025-04-01 16:15:20 +02:00
|
|
|
// Context
|
|
|
|
import { LoadingStatusContext } from '@freesewing/react/context/LoadingStatus'
|
|
|
|
// Hooks
|
2025-05-30 11:29:55 +02:00
|
|
|
import { useState, useContext } from 'react'
|
2025-04-01 16:15:20 +02:00
|
|
|
import { useAccount } from '@freesewing/react/hooks/useAccount'
|
|
|
|
import { useBackend } from '@freesewing/react/hooks/useBackend'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Control can be updated from many places in the UI.
|
|
|
|
* So this shared state handler keeps this DRY
|
|
|
|
*/
|
|
|
|
export const useControl = () => {
|
|
|
|
// Hooks
|
|
|
|
const backend = useBackend()
|
|
|
|
const { account, setAccount, token } = useAccount()
|
|
|
|
const { setLoadingStatus } = useContext(LoadingStatusContext)
|
|
|
|
|
|
|
|
// State
|
2025-05-29 17:43:10 +02:00
|
|
|
const [control, __setControl] = useState(account.control)
|
2025-04-01 16:15:20 +02:00
|
|
|
|
2025-05-29 17:43:10 +02:00
|
|
|
/*
|
|
|
|
* Legacy method to update the control setting
|
|
|
|
* Deprecated because its naming is inconsistent with other hooks
|
|
|
|
*/
|
2025-04-01 16:15:20 +02:00
|
|
|
const updateControl = async (newControl) => {
|
2025-05-29 17:43:10 +02:00
|
|
|
console.warn('The updateControl method is deprecated. Use setControl instead.')
|
|
|
|
return setControl(newControl)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Method to set the control setting
|
|
|
|
const setControl = async (newControl) => {
|
2025-04-01 16:15:20 +02:00
|
|
|
if (newControl !== control) {
|
|
|
|
if (token) {
|
|
|
|
setLoadingStatus([true, 'Updating preferences'])
|
|
|
|
const [status, body] = await backend.updateAccount({ control: newControl })
|
|
|
|
if (status === 200) {
|
2025-05-29 17:43:10 +02:00
|
|
|
__setControl(newControl)
|
2025-04-01 16:15:20 +02:00
|
|
|
setAccount(body.account)
|
|
|
|
setLoadingStatus([true, 'Preferences updated', true, true])
|
|
|
|
} else
|
|
|
|
setLoadingStatus([true, 'Failed to update preferences. Please report this', true, true])
|
|
|
|
} else {
|
|
|
|
/*
|
|
|
|
* Control is used even when people are not logged in
|
|
|
|
* So this ensures control is always available, even if people are not authenticated
|
|
|
|
*/
|
|
|
|
setAccount({ ...account, control: newControl })
|
2025-05-29 17:43:10 +02:00
|
|
|
__setControl(newControl)
|
2025-04-01 16:15:20 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-05-29 17:43:10 +02:00
|
|
|
return { control, setControl, updateControl }
|
2025-04-01 16:15:20 +02:00
|
|
|
}
|