2022-12-27 14:54:21 -05:00
|
|
|
import { useCallback } from 'react'
|
|
|
|
import { useEditorContext } from '../../../shared/context/editor-context'
|
|
|
|
import useScopeValue from '../../../shared/hooks/use-scope-value'
|
2023-01-06 20:45:37 -05:00
|
|
|
import type { ProjectSettings } from '../utils/api'
|
|
|
|
import useSaveProjectSettings from './use-save-project-settings'
|
2022-12-27 14:54:21 -05:00
|
|
|
|
2023-01-03 17:33:31 -05:00
|
|
|
export default function useRootDocId() {
|
2023-01-06 20:45:37 -05:00
|
|
|
const [rootDocId] =
|
2023-01-04 07:17:50 -05:00
|
|
|
useScopeValue<ProjectSettings['rootDocId']>('project.rootDoc_id')
|
2022-12-27 14:54:21 -05:00
|
|
|
const { permissionsLevel } = useEditorContext()
|
2023-01-06 20:45:37 -05:00
|
|
|
const saveProjectSettings = useSaveProjectSettings()
|
2022-12-27 14:54:21 -05:00
|
|
|
|
2023-01-03 17:33:31 -05:00
|
|
|
const setRootDocIdFunc = useCallback(
|
2023-01-04 07:17:50 -05:00
|
|
|
async (newRootDocId: ProjectSettings['rootDocId']) => {
|
2023-01-06 20:45:37 -05:00
|
|
|
// rootDoc_id will be undefined on angular scope on initialisation
|
2022-12-28 15:58:14 -05:00
|
|
|
const allowUpdate =
|
2023-01-06 20:45:37 -05:00
|
|
|
typeof rootDocId !== 'undefined' && permissionsLevel !== 'readOnly'
|
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-06 20:45:37 -05:00
|
|
|
await saveProjectSettings('rootDocId', 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-06 20:45:37 -05:00
|
|
|
[permissionsLevel, rootDocId, saveProjectSettings]
|
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
|
|
|
}
|