file-name-input.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import {
  2. DetailedHTMLProps,
  3. InputHTMLAttributes,
  4. useCallback,
  5. useEffect,
  6. useState,
  7. } from 'react'
  8. import { File, FileOrDirectory } from '../../utils/file'
  9. import useScopeValue from '../../../../shared/hooks/use-scope-value'
  10. import { Alert } from 'react-bootstrap'
  11. type FileNameInputProps = Omit<
  12. DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>,
  13. 'onFocus'
  14. > & { targetFolder: File | null }
  15. function findFile(
  16. folder: { id: string; name: string },
  17. project: FileOrDirectory
  18. ): FileOrDirectory | null {
  19. if (project.id === folder.id) {
  20. return project
  21. }
  22. if (project.type !== 'folder') {
  23. return null
  24. }
  25. for (const child of project.children ?? []) {
  26. const search = findFile(folder, child)
  27. if (search) {
  28. return search
  29. }
  30. }
  31. return null
  32. }
  33. function hasOverlap(
  34. name: string,
  35. folder: { id: string; name: string },
  36. project: FileOrDirectory
  37. ): boolean {
  38. const directory = findFile(folder, project)
  39. if (!directory) {
  40. return false
  41. }
  42. for (const child of directory.children ?? []) {
  43. if (child.name === name) {
  44. return true
  45. }
  46. }
  47. return false
  48. }
  49. export const FileNameInput = ({
  50. targetFolder,
  51. ...props
  52. }: FileNameInputProps) => {
  53. const [overlap, setOverlap] = useState<boolean>(false)
  54. const [rootFolder] = useScopeValue<FileOrDirectory>('rootFolder')
  55. const { value } = props
  56. useEffect(() => {
  57. if (value) {
  58. setOverlap(
  59. hasOverlap(String(value), targetFolder ?? rootFolder, rootFolder)
  60. )
  61. } else {
  62. setOverlap(false)
  63. }
  64. }, [value, targetFolder, rootFolder])
  65. const onFocus = useCallback((event: React.FocusEvent<HTMLInputElement>) => {
  66. if (!event.target) {
  67. return true
  68. }
  69. const fileName = event.target.value
  70. const fileExtensionIndex = fileName.lastIndexOf('.')
  71. if (fileExtensionIndex >= 0) {
  72. event.target.setSelectionRange(0, fileExtensionIndex)
  73. }
  74. }, [])
  75. return (
  76. <>
  77. <input {...props} type="text" onFocus={onFocus} />
  78. {overlap && (
  79. <Alert bsStyle="warning" className="mt-1 mb-0">
  80. A file with that name already exists. That file will be overwritten.
  81. </Alert>
  82. )}
  83. </>
  84. )
  85. }