| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- import React, {
- useCallback, useState, FC, useEffect, memo,
- } from 'react';
- import nodePath from 'path';
- import { useTranslation } from 'react-i18next';
- import { pagePathUtils } from '@growi/core';
- import { useDrag, useDrop } from 'react-dnd';
- import { toastWarning, toastError } from '~/client/util/apiNotification';
- import { ItemNode } from './ItemNode';
- import { IPageHasId } from '~/interfaces/page';
- import { useSWRxPageChildren } from '../../../stores/page-listing';
- import ClosableTextInput, { AlertInfo, AlertType } from '../../Common/ClosableTextInput';
- import PageItemControl from '../../Common/Dropdown/PageItemControl';
- import { IPageForPageDeleteModal } from '~/components/PageDeleteModal';
- import { apiv3Put } from '~/client/util/apiv3-client';
- import TriangleIcon from '~/components/Icons/TriangleIcon';
- const { isTopPage } = pagePathUtils;
- interface ItemProps {
- isEnableActions: boolean
- itemNode: ItemNode
- targetPathOrId?: string
- isOpen?: boolean
- onClickDeleteByPage?(page: IPageForPageDeleteModal): void
- }
- // Utility to mark target
- const markTarget = (children: ItemNode[], targetPathOrId?: string): void => {
- if (targetPathOrId == null) {
- return;
- }
- children.forEach((node) => {
- if (node.page._id === targetPathOrId || node.page.path === targetPathOrId) {
- node.page.isTarget = true;
- }
- return node;
- });
- };
- type ItemControlProps = {
- page: Partial<IPageHasId>
- isEnableActions: boolean
- isDeletable: boolean
- onClickPlusButton?(): void
- onClickDeleteButton?(): void
- onClickRenameButton?(): void
- }
- const ItemControl: FC<ItemControlProps> = memo((props: ItemControlProps) => {
- const onClickPlusButton = () => {
- if (props.onClickPlusButton == null) {
- return;
- }
- props.onClickPlusButton();
- };
- const onClickDeleteButtonHandler = () => {
- if (props.onClickDeleteButton == null) {
- return;
- }
- props.onClickDeleteButton();
- };
- const onClickRenameButtonHandler = () => {
- if (props.onClickRenameButton == null) {
- return;
- }
- props.onClickRenameButton();
- };
- if (props.page == null) {
- return <></>;
- }
- return (
- <>
- <PageItemControl
- page={props.page}
- onClickDeleteButtonHandler={onClickDeleteButtonHandler}
- isEnableActions={props.isEnableActions}
- isDeletable={props.isDeletable}
- onClickRenameButtonHandler={onClickRenameButtonHandler}
- />
- <button
- type="button"
- className="border-0 rounded grw-btn-page-management p-0"
- onClick={onClickPlusButton}
- >
- <i className="icon-plus text-muted d-block p-1" />
- </button>
- </>
- );
- });
- const ItemCount: FC = () => {
- return (
- <>
- <span className="grw-pagetree-count badge badge-pill badge-light text-muted">
- {/* TODO: consider to show the number of children pages */}
- 00
- </span>
- </>
- );
- };
- const Item: FC<ItemProps> = (props: ItemProps) => {
- const { t } = useTranslation();
- const {
- itemNode, targetPathOrId, isOpen: _isOpen = false, onClickDeleteByPage, isEnableActions,
- } = props;
- const { page, children } = itemNode;
- const [pageTitle, setPageTitle] = useState(page.path);
- const [currentChildren, setCurrentChildren] = useState(children);
- const [isOpen, setIsOpen] = useState(_isOpen);
- const [isNewPageInputShown, setNewPageInputShown] = useState(false);
- const [isRenameInputShown, setRenameInputShown] = useState(false);
- const { data, error } = useSWRxPageChildren(isOpen ? page._id : null);
- const [{ isDragging }, drag] = useDrag(() => ({
- type: 'PAGE_TREE',
- item: { page },
- collect: monitor => ({
- isDragging: monitor.isDragging(),
- }),
- }));
- const pageItemDropHandler = () => {
- // TODO: hit an api to rename the page by 85175
- // eslint-disable-next-line no-console
- console.log('pageItem was droped!!');
- };
- const [{ isOver }, drop] = useDrop(() => ({
- accept: 'PAGE_TREE',
- drop: pageItemDropHandler,
- hover: (item, monitor) => {
- // when a drag item is overlapped more than 1 sec, the drop target item will be opened.
- if (monitor.isOver()) {
- setTimeout(() => {
- if (monitor.isOver()) {
- setIsOpen(true);
- }
- }, 1000);
- }
- },
- collect: monitor => ({
- isOver: monitor.isOver(),
- }),
- }));
- const hasChildren = useCallback((): boolean => {
- return currentChildren != null && currentChildren.length > 0;
- }, [currentChildren]);
- const onClickLoadChildren = useCallback(async() => {
- setIsOpen(!isOpen);
- }, [isOpen]);
- const onClickPlusButton = useCallback(() => {
- setNewPageInputShown(true);
- }, []);
- const onClickDeleteButton = useCallback(() => {
- if (onClickDeleteByPage == null) {
- return;
- }
- const { _id: pageId, revision: revisionId, path } = page;
- if (pageId == null || revisionId == null || path == null) {
- throw Error('Any of _id, revision, and path must not be null.');
- }
- const pageToDelete: IPageForPageDeleteModal = {
- pageId,
- revisionId: revisionId as string,
- path,
- };
- onClickDeleteByPage(pageToDelete);
- }, [page, onClickDeleteByPage]);
- const onClickRenameButton = useCallback(() => {
- setRenameInputShown(true);
- }, []);
- // TODO: make a put request to pages/title
- const onPressEnterForRenameHandler = async(inputText: string) => {
- if (inputText.includes('/')) {
- toastWarning('Cannot rename a title that contains "/"');
- return;
- }
- const parentPath = nodePath.dirname(page.path as string || '/');
- const childPath = nodePath.basename(inputText);
- const newPagePath = `${parentPath}/${childPath}`;
- try {
- const res = await apiv3Put('pages/rename', { newPagePath, pageId: page._id, revisionId: page.revision });
- const title = nodePath.basename(res.data.page.path);
- setPageTitle(title);
- }
- catch (err) {
- toastError(err);
- }
- finally {
- setRenameInputShown(false);
- }
- };
- // TODO: go to create page page
- const onPressEnterForCreateHandler = () => {
- toastWarning(t('search_result.currently_not_implemented'));
- setNewPageInputShown(false);
- };
- const inputValidator = (title: string | null): AlertInfo | null => {
- if (title == null || title === '') {
- return {
- type: AlertType.WARNING,
- message: t('form_validation.title_required'),
- };
- }
- return null;
- };
- // didMount
- useEffect(() => {
- if (hasChildren()) setIsOpen(true);
- }, []);
- /*
- * Make sure itemNode.children and currentChildren are synced
- */
- useEffect(() => {
- if (children.length > currentChildren.length) {
- markTarget(children, targetPathOrId);
- setCurrentChildren(children);
- }
- }, []);
- /*
- * When swr fetch succeeded
- */
- useEffect(() => {
- if (isOpen && error == null && data != null) {
- const newChildren = ItemNode.generateNodesFromPages(data.children);
- markTarget(newChildren, targetPathOrId);
- setCurrentChildren(newChildren);
- }
- }, [data, isOpen]);
- return (
- <div className={`grw-pagetree-item-container ${isOver ? 'grw-pagetree-is-over' : ''}`}>
- <li
- ref={(c) => { drag(c); drop(c) }}
- className={`list-group-item list-group-item-action border-0 py-1 d-flex align-items-center ${page.isTarget ? 'grw-pagetree-is-target' : ''}`}
- >
- <button
- type="button"
- className={`grw-pagetree-button btn ${isOpen ? 'grw-pagetree-open' : ''}`}
- onClick={onClickLoadChildren}
- >
- <div className="grw-triangle-icon">
- <TriangleIcon />
- </div>
- </button>
- { isRenameInputShown && (
- <ClosableTextInput
- isShown
- placeholder={t('Input page name')}
- onClickOutside={() => { setRenameInputShown(false) }}
- onPressEnter={onPressEnterForRenameHandler}
- inputValidator={inputValidator}
- />
- )}
- { !isRenameInputShown && (
- <a href={page._id} className="grw-pagetree-title-anchor flex-grow-1">
- <p className={`text-truncate m-auto ${page.isEmpty && 'text-muted'}`}>{nodePath.basename(pageTitle as string) || '/'}</p>
- </a>
- )}
- <div className="grw-pagetree-count-wrapper">
- <ItemCount />
- </div>
- <div className="grw-pagetree-control d-none">
- <ItemControl
- page={page}
- onClickPlusButton={onClickPlusButton}
- onClickDeleteButton={onClickDeleteButton}
- onClickRenameButton={onClickRenameButton}
- isEnableActions={isEnableActions}
- isDeletable={!page.isEmpty && !isTopPage(page.path as string)}
- />
- </div>
- </li>
- {isEnableActions && (
- <ClosableTextInput
- isShown={isNewPageInputShown}
- placeholder={t('Input page name')}
- onClickOutside={() => { setNewPageInputShown(false) }}
- onPressEnter={onPressEnterForCreateHandler}
- inputValidator={inputValidator}
- />
- )}
- {
- isOpen && hasChildren() && currentChildren.map(node => (
- <div key={node.page._id} className="grw-pagetree-item-children">
- <Item
- isEnableActions={isEnableActions}
- itemNode={node}
- isOpen={false}
- targetPathOrId={targetPathOrId}
- onClickDeleteByPage={onClickDeleteByPage}
- />
- </div>
- ))
- }
- </div>
- );
- };
- export default Item;
|