mirror of
https://github.com/overleaf/overleaf.git
synced 2024-11-14 20:40:17 -05:00
7c97f8ab6e
* Use new JSX runtime and update Babel Node target * Update .eslintrc * Remove React imports GitOrigin-RevId: 559de0267f8f2934c56a860ea8701bb522aa861a
52 lines
1.2 KiB
JavaScript
52 lines
1.2 KiB
JavaScript
import { createContext, useContext, useMemo, useReducer } from 'react'
|
|
import { isCleanFilename } from '../util/safe-path'
|
|
import PropTypes from 'prop-types'
|
|
|
|
const FileTreeCreateNameContext = createContext()
|
|
|
|
export const useFileTreeCreateName = () => {
|
|
const context = useContext(FileTreeCreateNameContext)
|
|
|
|
if (!context) {
|
|
throw new Error(
|
|
'useFileTreeCreateName is only available inside FileTreeCreateNameProvider'
|
|
)
|
|
}
|
|
|
|
return context
|
|
}
|
|
|
|
export default function FileTreeCreateNameProvider({
|
|
children,
|
|
initialName = '',
|
|
}) {
|
|
const [state, setName] = useReducer(
|
|
(state, name) => ({
|
|
name, // the file name
|
|
touchedName: true, // whether the name has been edited
|
|
}),
|
|
{
|
|
name: initialName,
|
|
touchedName: false,
|
|
}
|
|
)
|
|
|
|
// validate the file name
|
|
const validName = useMemo(() => isCleanFilename(state.name.trim()), [state])
|
|
|
|
return (
|
|
<FileTreeCreateNameContext.Provider
|
|
value={{ ...state, setName, validName }}
|
|
>
|
|
{children}
|
|
</FileTreeCreateNameContext.Provider>
|
|
)
|
|
}
|
|
|
|
FileTreeCreateNameProvider.propTypes = {
|
|
children: PropTypes.oneOfType([
|
|
PropTypes.arrayOf(PropTypes.node),
|
|
PropTypes.node,
|
|
]).isRequired,
|
|
initialName: PropTypes.string,
|
|
}
|