PageTitleHeader.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import type { FC } from 'react';
  2. import { useState, useMemo, useCallback } from 'react';
  3. import nodePath from 'path';
  4. import { pathUtils } from '@growi/core/dist/utils';
  5. import type { Props } from './PagePathHeader';
  6. import { TextInputForPageTitleAndPath } from './TextInputForPageTitleAndPath';
  7. import { usePagePathRenameHandler } from './page-header-utils';
  8. export const PageTitleHeader: FC<Props> = (props) => {
  9. const { currentPage } = props;
  10. const currentPagePath = currentPage.path;
  11. const pageTitle = nodePath.basename(currentPagePath) || '/';
  12. const [isRenameInputShown, setRenameInputShown] = useState(false);
  13. const [editedPagePath, setEditedPagePath] = useState(currentPagePath);
  14. const editedPageTitle = nodePath.basename(editedPagePath);
  15. const onRenameFinish = () => {
  16. setRenameInputShown(false);
  17. };
  18. const onRenameFailure = () => {
  19. setRenameInputShown(true);
  20. };
  21. const onInputChange = useCallback((inputText: string) => {
  22. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(currentPage?.path ?? ''));
  23. const newPagePath = nodePath.resolve(parentPath, inputText);
  24. setEditedPagePath(newPagePath);
  25. }, [currentPage?.path, setEditedPagePath]);
  26. const onPressEscape = () => {
  27. setEditedPagePath(currentPagePath);
  28. setRenameInputShown(false);
  29. };
  30. const onClickPageTitle = () => {
  31. console.log(currentPagePath);
  32. setEditedPagePath(currentPagePath);
  33. setRenameInputShown(true);
  34. };
  35. const pagePathRenameHandler = usePagePathRenameHandler(currentPage);
  36. const stateHandler = { isRenameInputShown, setRenameInputShown };
  37. const PageTitle = useMemo(() => (<div onClick={onClickPageTitle}>{pageTitle}</div>), [pageTitle]);
  38. const buttonStyle = isRenameInputShown ? '' : 'd-none';
  39. const onClickButton = () => {
  40. pagePathRenameHandler(editedPagePath, onRenameFinish, onRenameFailure);
  41. };
  42. return (
  43. <div className="row">
  44. <div className="col-4">
  45. <TextInputForPageTitleAndPath
  46. currentPage={currentPage}
  47. stateHandler={stateHandler}
  48. inputValue={editedPageTitle}
  49. CustomComponent={PageTitle}
  50. onInputChange={onInputChange}
  51. onPressEscape={onPressEscape}
  52. />
  53. </div>
  54. <div className={`col-4 ${buttonStyle}`}>
  55. <button type="button" onClick={onClickButton}>
  56. <span className="material-symbols-outlined">check_circle</span>
  57. </button>
  58. </div>
  59. </div>
  60. );
  61. };