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 17:33:31 -05:00
|
|
|
export default function useRootDocId() {
|
|
|
|
const [rootDocId, setRootDocId] =
|
|
|
|
useScopeValue<ProjectSettingsScope['rootDocId']>('project.rootDoc_id')
|
2022-12-27 14:54:21 -05:00
|
|
|
const { permissionsLevel } = useEditorContext()
|
|
|
|
const { _id: projectId } = useProjectContext()
|
|
|
|
|
2023-01-03 17:33:31 -05:00
|
|
|
const setRootDocIdFunc = useCallback(
|
|
|
|
async (newRootDocId: ProjectSettingsScope['rootDocId']) => {
|
2022-12-28 15:58:14 -05:00
|
|
|
const allowUpdate =
|
2023-01-03 17:33:31 -05:00
|
|
|
typeof rootDocId !== 'undefined' &&
|
2022-12-28 15:58:14 -05:00
|
|
|
permissionsLevel !== 'readOnly' &&
|
2023-01-03 17:33:31 -05:00
|
|
|
rootDocId !== newRootDocId
|
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 {
|
2023-01-03 17:33:31 -05:00
|
|
|
await saveProjectSettings({ projectId, rootDocId: newRootDocId })
|
|
|
|
setRootDocId(newRootDocId)
|
2022-12-27 14:54:21 -05:00
|
|
|
} catch (err) {
|
|
|
|
// TODO: retry mechanism (max 10x before failed completely and rollback the old value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2023-01-03 17:33:31 -05:00
|
|
|
[permissionsLevel, projectId, rootDocId, setRootDocId]
|
2022-12-27 14:54:21 -05:00
|
|
|
)
|
2023-01-03 17:33:31 -05:00
|
|
|
|
|
|
|
return {
|
|
|
|
rootDocId,
|
|
|
|
setRootDocId: setRootDocIdFunc,
|
|
|
|
}
|
2022-12-27 14:54:21 -05:00
|
|
|
}
|