overleaf/services/web/frontend/js/features/editor-left-menu/hooks/use-root-doc-id.tsx
M Fahru 4548f504f7 standardize the naming for rootDocId.
- Remove the `scope` variable suffix
- change `rootDoc_id` to `rootDocId`

GitOrigin-RevId: d8e646ef5f99ba0dbce84ff63c588e63b956a4ec
2023-01-11 09:09:04 +00:00

36 lines
1.2 KiB
TypeScript

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'
import { type ProjectSettingsScope, saveProjectSettings } from '../utils/api'
export default function useRootDocId() {
const [rootDocId, setRootDocId] =
useScopeValue<ProjectSettingsScope['rootDocId']>('project.rootDoc_id')
const { permissionsLevel } = useEditorContext()
const { _id: projectId } = useProjectContext()
const setRootDocIdFunc = useCallback(
async (newRootDocId: ProjectSettingsScope['rootDocId']) => {
const allowUpdate =
typeof rootDocId !== 'undefined' &&
permissionsLevel !== 'readOnly' &&
rootDocId !== newRootDocId
if (allowUpdate) {
try {
await saveProjectSettings({ projectId, rootDocId: newRootDocId })
setRootDocId(newRootDocId)
} catch (err) {
// TODO: retry mechanism (max 10x before failed completely and rollback the old value)
}
}
},
[permissionsLevel, projectId, rootDocId, setRootDocId]
)
return {
rootDocId,
setRootDocId: setRootDocIdFunc,
}
}