2022-12-27 14:54:21 -05:00
|
|
|
import { useCallback } from 'react'
|
|
|
|
import { useEditorContext } from '../../../shared/context/editor-context'
|
|
|
|
import { useProjectContext } from '../../../shared/context/project-context'
|
|
|
|
import useScopeValue from '../../../shared/hooks/use-scope-value'
|
2023-01-03 12:46:37 -05:00
|
|
|
import { type ProjectSettingsScope, saveProjectSettings } from '../utils/api'
|
2022-12-27 14:54:21 -05:00
|
|
|
|
2023-01-03 12:04:34 -05:00
|
|
|
export default function useSetRootDocId() {
|
2022-12-27 14:54:21 -05:00
|
|
|
const [rootDocIdScope, setRootDocIdScope] =
|
2023-01-03 12:46:37 -05:00
|
|
|
useScopeValue<ProjectSettingsScope['rootDoc_id']>('project.rootDoc_id')
|
2022-12-27 14:54:21 -05:00
|
|
|
const { permissionsLevel } = useEditorContext()
|
|
|
|
const { _id: projectId } = useProjectContext()
|
|
|
|
|
|
|
|
const setRootDocId = useCallback(
|
2023-01-03 12:46:37 -05:00
|
|
|
async (rootDocId: ProjectSettingsScope['rootDoc_id']) => {
|
2022-12-28 15:58:14 -05:00
|
|
|
const allowUpdate =
|
|
|
|
typeof rootDocIdScope !== 'undefined' &&
|
|
|
|
permissionsLevel !== 'readOnly' &&
|
|
|
|
rootDocIdScope !== rootDocId
|
2022-12-27 14:54:21 -05:00
|
|
|
|
2022-12-28 15:58:14 -05:00
|
|
|
if (allowUpdate) {
|
2022-12-27 14:54:21 -05:00
|
|
|
try {
|
2022-12-28 12:38:27 -05:00
|
|
|
await saveProjectSettings({ projectId, rootDoc_id: rootDocId })
|
2022-12-27 14:54:21 -05:00
|
|
|
setRootDocIdScope(rootDocId)
|
|
|
|
} catch (err) {
|
|
|
|
// TODO: retry mechanism (max 10x before failed completely and rollback the old value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2023-01-03 12:04:34 -05:00
|
|
|
[permissionsLevel, projectId, rootDocIdScope, setRootDocIdScope]
|
2022-12-27 14:54:21 -05:00
|
|
|
)
|
|
|
|
return setRootDocId
|
|
|
|
}
|