2021-03-18 05:52:36 -04:00
|
|
|
import React, { 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,
|
2021-04-27 03:52:58 -04:00
|
|
|
initialName = '',
|
2021-03-18 05:52:36 -04:00
|
|
|
}) {
|
|
|
|
const [state, setName] = useReducer(
|
|
|
|
(state, name) => ({
|
|
|
|
name, // the file name
|
2021-04-27 03:52:58 -04:00
|
|
|
touchedName: true, // whether the name has been edited
|
2021-03-18 05:52:36 -04:00
|
|
|
}),
|
|
|
|
{
|
|
|
|
name: initialName,
|
2021-04-27 03:52:58 -04:00
|
|
|
touchedName: false,
|
2021-03-18 05:52:36 -04:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// 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),
|
2021-04-27 03:52:58 -04:00
|
|
|
PropTypes.node,
|
2021-03-18 05:52:36 -04:00
|
|
|
]).isRequired,
|
2021-04-27 03:52:58 -04:00
|
|
|
initialName: PropTypes.string,
|
2021-03-18 05:52:36 -04:00
|
|
|
}
|