Просмотр исходного кода

Merge branch 'master' into fix/87892-fix-pt-scroll

* master: (91 commits)
  add '3' VRT tests in CI
  add VRT test for Mathjax
  move VRT examples
  fix lint errors
  add test for checkboxes behaviors
  add VRT test
  add a new test for search page
  BugFix
  fix lint errors
  fix lint errors
  fix lint errors
  fix type problems
  add missing method
  re-impl checkbox management
  BugFix for deselectAll
  use custom imput
  clean code
  Fixed process
  Fixed & Removed resolved comments
  Fixed process
  ...
Mao 4 лет назад
Родитель
Сommit
c6efed68e8
51 измененных файлов с 1177 добавлено и 921 удалено
  1. 1 1
      .github/workflows/reusable-app-prod.yml
  2. 2 0
      packages/app/resource/locales/en_US/translation.json
  3. 2 0
      packages/app/resource/locales/ja_JP/translation.json
  4. 2 0
      packages/app/resource/locales/zh_CN/translation.json
  5. 2 2
      packages/app/src/client/app.jsx
  6. 13 0
      packages/app/src/client/interfaces/selectable-all.ts
  7. 1 1
      packages/app/src/components/Common/ClosableTextInput.tsx
  8. 2 2
      packages/app/src/components/Common/Dropdown/PageItemControl.tsx
  9. 0 1
      packages/app/src/components/IdenticalPathPage.tsx
  10. 1 1
      packages/app/src/components/Page/RevisionLoader.jsx
  11. 10 5
      packages/app/src/components/Page/RevisionRenderer.jsx
  12. 40 14
      packages/app/src/components/PageList/PageListItemL.tsx
  13. 1 1
      packages/app/src/components/PaginationWrapper.tsx
  14. 0 396
      packages/app/src/components/SearchPage.jsx
  15. 260 0
      packages/app/src/components/SearchPage.tsx
  16. 0 64
      packages/app/src/components/SearchPage/DeleteSelectedPageGroup.tsx
  17. 0 42
      packages/app/src/components/SearchPage/IncludeSpecificPathButton.jsx
  18. 74 0
      packages/app/src/components/SearchPage/OperateAllControl.tsx
  19. 72 91
      packages/app/src/components/SearchPage/SearchControl.tsx
  20. 22 23
      packages/app/src/components/SearchPage/SearchOptionModal.tsx
  21. 0 79
      packages/app/src/components/SearchPage/SearchPageLayout.tsx
  22. 8 10
      packages/app/src/components/SearchPage/SearchResultContent.tsx
  23. 53 39
      packages/app/src/components/SearchPage/SearchResultList.tsx
  24. 9 7
      packages/app/src/components/SearchPage/SortControl.tsx
  25. 166 0
      packages/app/src/components/SearchPage2/SearchPageBase.tsx
  26. 31 5
      packages/app/src/components/Sidebar/PageTree/Item.tsx
  27. 4 1
      packages/app/src/components/Sidebar/PageTree/ItemsTree.tsx
  28. 9 13
      packages/app/src/interfaces/search.ts
  29. 2 12
      packages/app/src/server/interfaces/search.ts
  30. 33 0
      packages/app/src/server/models/obsolete-page.js
  31. 17 2
      packages/app/src/server/models/page.ts
  32. 3 0
      packages/app/src/server/models/revision.js
  33. 8 4
      packages/app/src/server/routes/apiv3/pages.js
  34. 1 1
      packages/app/src/server/routes/page.js
  35. 16 8
      packages/app/src/server/service/page-grant.ts
  36. 99 44
      packages/app/src/server/service/page.ts
  37. 8 6
      packages/app/src/server/service/search-delegator/elasticsearch.ts
  38. 4 2
      packages/app/src/server/service/search-delegator/private-legacy-pages.ts
  39. 4 6
      packages/app/src/server/service/search.ts
  40. 15 8
      packages/app/src/server/service/user-group.ts
  41. 4 0
      packages/app/src/server/util/swigFunctions.js
  42. 2 2
      packages/app/src/server/views/widget/not_found_content.html
  43. 92 0
      packages/app/src/stores/search.tsx
  44. 10 24
      packages/app/src/styles/_search.scss
  45. 4 0
      packages/app/src/styles/atoms/_custom_control.scss
  46. 0 0
      packages/app/test/cypress/integration/0-advanced-examples/misc.spec.ts
  47. 0 0
      packages/app/test/cypress/integration/0-advanced-examples/viewport.spec.ts
  48. 6 1
      packages/app/test/cypress/integration/2-basic-features/access-to-page.spec.ts
  49. 48 0
      packages/app/test/cypress/integration/3-search/access-to-result-page-directly.spec.ts
  50. 5 3
      packages/core/src/utils/page-path-utils.ts
  51. 11 0
      packages/core/src/utils/path-utils.js

+ 1 - 1
.github/workflows/reusable-app-prod.yml

@@ -187,7 +187,7 @@ jobs:
       fail-fast: false
       matrix:
         # List string expressions that is comma separated ids of tests in "test/cypress/integration"
-        spec-group: ['1', '2']
+        spec-group: ['1', '2', '3']
 
     services:
       mongodb:

+ 2 - 0
packages/app/resource/locales/en_US/translation.json

@@ -167,6 +167,8 @@
   "new_path":"New path",
   "duplicated_path":"duplicated_path",
   "Link sharing is disabled": "Link sharing is disabled",
+  "successfully_saved_the_page": "Successfully saved the page",
+  "you_can_not_create_page_with_this_name": "You can not create page with this name",
   "personal_dropdown": {
     "home": "Home",
     "settings": "Settings",

+ 2 - 0
packages/app/resource/locales/ja_JP/translation.json

@@ -169,6 +169,8 @@
   "new_path":"新しいパス",
   "duplicated_path":"重複したパス",
   "Link sharing is disabled": "リンクのシェアは無効化されています",
+  "successfully_saved_the_page": "ページが正常に保存されました",
+  "you_can_not_create_page_with_this_name": "この名前でページを作成することはできません",
   "personal_dropdown": {
     "home": "ホーム",
     "settings": "設定",

+ 2 - 0
packages/app/resource/locales/zh_CN/translation.json

@@ -175,6 +175,8 @@
   "new_path":"New path",
   "duplicated_path":"duplicated_path",
   "Link sharing is disabled": "你不允许分享该链接",
+  "successfully_saved_the_page": "成功地保存了该页面",
+  "you_can_not_create_page_with_this_name": "您无法使用此名称创建页面",
 	"form_validation": {
 		"error_message": "有些值不正确",
 		"required": "%s 是必需的",

+ 2 - 2
packages/app/src/client/app.jsx

@@ -13,7 +13,7 @@ import { swrGlobalConfiguration } from '~/utils/swr-utils';
 import InAppNotificationPage from '../components/InAppNotification/InAppNotificationPage';
 import ErrorBoundary from '../components/ErrorBoudary';
 import Sidebar from '../components/Sidebar';
-import SearchPage from '../components/SearchPage';
+import { SearchPage } from '../components/SearchPage';
 import TagsList from '../components/TagsList';
 import DisplaySwitcher from '../components/Page/DisplaySwitcher';
 import { defaultEditorOptions, defaultPreviewOptions } from '../components/PageEditor/OptionsSelector';
@@ -85,7 +85,7 @@ logger.info('unstated containers have been initialized');
 Object.assign(componentMappings, {
   'grw-sidebar-wrapper': <Sidebar />,
 
-  'search-page': <SearchPage crowi={appContainer} />,
+  'search-page': <SearchPage appContainer={appContainer} />,
   'all-in-app-notifications': <InAppNotificationPage />,
   'identical-path-page': <IdenticalPathPage />,
 

+ 13 - 0
packages/app/src/client/interfaces/selectable-all.ts

@@ -0,0 +1,13 @@
+export interface ISelectable {
+  select: () => void,
+  deselect: () => void,
+}
+
+export interface ISelectableAndIndeterminatable extends ISelectable {
+  setIndeterminate: () => void,
+}
+
+export interface ISelectableAll {
+  selectAll: () => void,
+  deselectAll: () => void,
+}

+ 1 - 1
packages/app/src/components/Common/ClosableTextInput.tsx

@@ -107,7 +107,7 @@ const ClosableTextInput: FC<ClosableTextInputProps> = memo((props: ClosableTextI
   return (
     <div className={props.isShown ? 'd-block' : 'd-none'}>
       <input
-        value={inputText}
+        value={inputText || ''}
         ref={inputRef}
         type="text"
         className="form-control"

+ 2 - 2
packages/app/src/components/Common/Dropdown/PageItemControl.tsx

@@ -112,7 +112,7 @@ const PageItemControlDropdownMenu = React.memo((props: DropdownMenuProps): JSX.E
         ) }
 
         {/* Duplicate */}
-        { isEnableActions && !pageInfo.isEmpty && (
+        { isEnableActions && (
           <DropdownItem onClick={duplicateItemClickedHandler}>
             <i className="icon-fw icon-docs"></i>
             {t('Duplicate')}
@@ -131,7 +131,7 @@ const PageItemControlDropdownMenu = React.memo((props: DropdownMenuProps): JSX.E
 
         {/* divider */}
         {/* Delete */}
-        { isEnableActions && pageInfo.isMovable && !pageInfo.isEmpty && (
+        { isEnableActions && pageInfo.isMovable && (
           <>
             <DropdownItem divider />
             <DropdownItem

+ 0 - 1
packages/app/src/components/IdenticalPathPage.tsx

@@ -109,7 +109,6 @@ const IdenticalPathPage:FC<IdenticalPathPageProps> = (props: IdenticalPathPagePr
                   key={pageId}
                   page={pageWithMeta}
                   isSelected={false}
-                  isChecked={false}
                   isEnableActions
                   showPageUpdatedTime
                 // Todo: add onClickDeleteButton when delete feature implemented

+ 1 - 1
packages/app/src/components/Page/RevisionLoader.jsx

@@ -126,7 +126,7 @@ LegacyRevisionLoader.propTypes = {
   revisionId: PropTypes.string.isRequired,
   lazy: PropTypes.bool,
   onRevisionLoaded: PropTypes.func,
-  highlightKeywords: PropTypes.string,
+  highlightKeywords: PropTypes.arrayOf(PropTypes.string),
 };
 
 const RevisionLoader = (props) => {

+ 10 - 5
packages/app/src/components/Page/RevisionRenderer.jsx

@@ -62,13 +62,18 @@ class LegacyRevisionRenderer extends React.PureComponent {
    * @param {string} body html strings
    * @param {string} keywords
    */
-  getHighlightedBody(body, keywords) {
+  getHighlightedBody(body, _keywords) {
+    const keywords = Array.isArray(_keywords)
+      ? _keywords
+      : [_keywords];
+
     const normalizedKeywordsArray = [];
     // !!TODO!!: add test code refs: https://redmine.weseek.co.jp/issues/86841
     // Separate keywords
     // - Surrounded by double quotation
     // - Split by both full-width and half-width spaces
-    [...keywords.match(/"[^"]+"|[^\u{20}\u{3000}]+/ug)].forEach((keyword, i) => {
+    // [...keywords.match(/"[^"]+"|[^\u{20}\u{3000}]+/ug)].forEach((keyword, i) => {
+    keywords.forEach((keyword, i) => {
       if (keyword === '') {
         return;
       }
@@ -138,7 +143,7 @@ class LegacyRevisionRenderer extends React.PureComponent {
     await interceptorManager.process('prePostProcess', context);
     context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
 
-    if (highlightKeywords != null) {
+    if (highlightKeywords != null && highlightKeywords.length > 0) {
       context.parsedHTML = this.getHighlightedBody(context.parsedHTML, highlightKeywords);
     }
     await interceptorManager.process('postPostProcess', context);
@@ -167,7 +172,7 @@ LegacyRevisionRenderer.propTypes = {
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
   markdown: PropTypes.string.isRequired,
-  highlightKeywords: PropTypes.string,
+  highlightKeywords: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
   additionalClassName: PropTypes.string,
 };
 
@@ -185,7 +190,7 @@ const RevisionRenderer = (props) => {
 RevisionRenderer.propTypes = {
   growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
   markdown: PropTypes.string.isRequired,
-  highlightKeywords: PropTypes.string,
+  highlightKeywords: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
   additionalClassName: PropTypes.string,
 };
 

+ 40 - 14
packages/app/src/components/PageList/PageListItemL.tsx

@@ -1,4 +1,9 @@
-import React, { memo, useCallback } from 'react';
+import React, {
+  forwardRef,
+  ForwardRefRenderFunction, memo, useCallback, useImperativeHandle, useRef,
+} from 'react';
+
+import { CustomInput } from 'reactstrap';
 
 import Clamp from 'react-multiline-clamp';
 import { format } from 'date-fns';
@@ -16,25 +21,44 @@ import { IPageSearchMeta, isIPageSearchMeta } from '~/interfaces/search';
 import { PageItemControl } from '../Common/Dropdown/PageItemControl';
 import LinkedPagePath from '~/models/linked-page-path';
 import PagePathHierarchicalLink from '../PagePathHierarchicalLink';
+import { ISelectable } from '~/client/interfaces/selectable-all';
 
 type Props = {
   page: IPageWithMeta | IPageWithMeta<IPageInfoAll & IPageSearchMeta>,
   isSelected?: boolean, // is item selected(focused)
-  isChecked?: boolean, // is checkbox of item checked
   isEnableActions?: boolean,
   showPageUpdatedTime?: boolean, // whether to show page's updated time at the top-right corner of item
-  onClickCheckbox?: (pageId: string) => void,
+  onCheckboxChanged?: (isChecked: boolean, pageId: string) => void,
   onClickItem?: (pageId: string) => void,
   onClickDeleteButton?: (pageId: string) => void,
 }
 
-export const PageListItemL = memo((props: Props): JSX.Element => {
+const PageListItemLSubstance: ForwardRefRenderFunction<ISelectable, Props> = (props: Props, ref): JSX.Element => {
   const {
     // todo: refactoring variable name to clear what changed
-    page: { pageData, pageMeta }, isSelected, onClickItem, onClickCheckbox, isChecked, isEnableActions,
+    page: { pageData, pageMeta }, isSelected, isEnableActions,
     showPageUpdatedTime,
+    onClickItem, onCheckboxChanged,
   } = props;
 
+  const inputRef = useRef<HTMLInputElement>(null);
+
+  // publish ISelectable methods
+  useImperativeHandle(ref, () => ({
+    select: () => {
+      const input = inputRef.current;
+      if (input != null) {
+        input.checked = true;
+      }
+    },
+    deselect: () => {
+      const input = inputRef.current;
+      if (input != null) {
+        input.checked = false;
+      }
+    },
+  }));
+
   const { data: isDeviceSmallerThanLg } = useIsDeviceSmallerThanLg();
   const { open: openDuplicateModal } = usePageDuplicateModal();
   const { open: openRenameModal } = usePageRenameModal();
@@ -70,7 +94,7 @@ export const PageListItemL = memo((props: Props): JSX.Element => {
     openRenameModal(pageId, revisionId as string, path);
   }, [openRenameModal, pageData]);
 
-  const styleListGroupItem = (!isDeviceSmallerThanLg && onClickCheckbox != null) ? 'list-group-item-action' : '';
+  const styleListGroupItem = (!isDeviceSmallerThanLg && onClickItem != null) ? 'list-group-item-action' : '';
   // background color of list item changes when class "active" exists under 'list-group-item'
   const styleActive = !isDeviceSmallerThanLg && isSelected ? 'active' : '';
 
@@ -85,14 +109,14 @@ export const PageListItemL = memo((props: Props): JSX.Element => {
       >
         <div className="d-flex">
           {/* checkbox */}
-          {onClickCheckbox != null && (
-            <div className="form-check d-flex align-items-center justify-content-center px-md-2 pl-3 pr-2 search-item-checkbox">
-              <input
-                className="form-check-input position-relative m-0"
+          {onCheckboxChanged != null && (
+            <div className="d-flex align-items-center justify-content-center pl-md-2 pl-3">
+              <CustomInput
                 type="checkbox"
-                id="flexCheckDefault"
-                onChange={() => { onClickCheckbox(pageData._id) }}
-                checked={isChecked}
+                id={`cbSelect-${pageData._id}`}
+                data-testid="cb-select"
+                innerRef={inputRef}
+                onChange={(e) => { onCheckboxChanged(e.target.checked, pageData._id) }}
               />
             </div>
           )}
@@ -156,4 +180,6 @@ export const PageListItemL = memo((props: Props): JSX.Element => {
       </div>
     </li>
   );
-});
+};
+
+export const PageListItemL = memo(forwardRef(PageListItemLSubstance));

+ 1 - 1
packages/app/src/components/PaginationWrapper.tsx

@@ -7,7 +7,7 @@ import { Pagination, PaginationItem, PaginationLink } from 'reactstrap';
 
 type Props = {
   activePage: number,
-  changePage?: (number) => void,
+  changePage?: (activePage: number) => void,
   totalItemsCount: number,
   pagingLimit?: number,
   align?: string,

+ 0 - 396
packages/app/src/components/SearchPage.jsx

@@ -1,396 +0,0 @@
-// This is the root component for #search-page
-
-import React from 'react';
-import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
-
-import {
-  DetachCodeBlockInterceptor,
-  RestoreCodeBlockInterceptor,
-} from '../client/util/interceptor/detach-code-blocks';
-
-import { withUnstatedContainers } from './UnstatedUtils';
-import AppContainer from '~/client/services/AppContainer';
-import { toastError } from '~/client/util/apiNotification';
-import SearchPageLayout from './SearchPage/SearchPageLayout';
-import SearchResultContent from './SearchPage/SearchResultContent';
-import SearchResultList from './SearchPage/SearchResultList';
-import SearchControl from './SearchPage/SearchControl';
-import { CheckboxType, SORT_AXIS, SORT_ORDER } from '~/interfaces/search';
-import PageDeleteModal from './PageDeleteModal';
-import { useIsGuestUser } from '~/stores/context';
-
-export const specificPathNames = {
-  user: '/user',
-  trash: '/trash',
-};
-class SearchPage extends React.Component {
-
-  constructor(props) {
-    super(props);
-    // NOTE : selectedPages is deletion related state, will be used later in story 77535, 77565.
-    // deletionModal, deletion related functions are all removed, add them back when necessary.
-    // i.e ) in story 77525 or any tasks implementing deletion functionalities
-    this.state = {
-      searchingKeyword: decodeURI(this.props.query.q) || '',
-      searchedKeyword: '',
-      searchResults: [],
-      searchResultMeta: {},
-      focusedSearchResultData: null,
-      selectedPagesIdList: new Set(),
-      searchResultCount: 0,
-      activePage: 1,
-      pagingLimit: this.props.appContainer.config.pageLimitationL || 50,
-      excludeUserPages: true,
-      excludeTrashPages: true,
-      sort: SORT_AXIS.RELATION_SCORE,
-      order: SORT_ORDER.DESC,
-      selectAllCheckboxType: CheckboxType.NONE_CHECKED,
-      isDeleteConfirmModalShown: false,
-      deleteTargetPageIds: new Set(),
-    };
-
-    // TODO: Move this code to the right place after completing the "omit unstated" initiative.
-    const { interceptorManager } = props.appContainer;
-    interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(props.appContainer), 10); // process as soon as possible
-    interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(props.appContainer), 900); // process as late as possible
-
-    this.changeURL = this.changeURL.bind(this);
-    this.search = this.search.bind(this);
-    this.onSearchInvoked = this.onSearchInvoked.bind(this);
-    this.selectPage = this.selectPage.bind(this);
-    this.toggleCheckBox = this.toggleCheckBox.bind(this);
-    this.switchExcludeUserPagesHandler = this.switchExcludeUserPagesHandler.bind(this);
-    this.switchExcludeTrashPagesHandler = this.switchExcludeTrashPagesHandler.bind(this);
-    this.onChangeSortInvoked = this.onChangeSortInvoked.bind(this);
-    this.onPagingNumberChanged = this.onPagingNumberChanged.bind(this);
-    this.onPagingLimitChanged = this.onPagingLimitChanged.bind(this);
-    this.deleteSinglePageButtonHandler = this.deleteSinglePageButtonHandler.bind(this);
-    this.deleteAllPagesButtonHandler = this.deleteAllPagesButtonHandler.bind(this);
-    this.closeDeleteConfirmModalHandler = this.closeDeleteConfirmModalHandler.bind(this);
-  }
-
-  componentDidMount() {
-    const keyword = this.state.searchingKeyword;
-    if (keyword !== '') {
-      this.search({ keyword });
-    }
-  }
-
-  static getQueryByLocation(location) {
-    const search = location.search || '';
-    const query = {};
-
-    search.replace(/^\?/, '').split('&').forEach((element) => {
-      const queryParts = element.split('=');
-      query[queryParts[0]] = decodeURIComponent(queryParts[1]).replace(/\+/g, ' ');
-    });
-
-    return query;
-  }
-
-  switchExcludeUserPagesHandler() {
-    this.setState({ excludeUserPages: !this.state.excludeUserPages });
-  }
-
-  switchExcludeTrashPagesHandler() {
-    this.setState({ excludeTrashPages: !this.state.excludeTrashPages });
-  }
-
-  onChangeSortInvoked(nextSort, nextOrder) {
-    this.setState({
-      sort: nextSort,
-      order: nextOrder,
-    });
-  }
-
-  changeURL(keyword, refreshHash) {
-    let hash = window.location.hash || '';
-    // TODO 整理する
-    if (refreshHash || this.state.searchedKeyword !== '') {
-      hash = '';
-    }
-    if (window.history && window.history.pushState) {
-      window.history.pushState('', `Search - ${keyword}`, `/_search?q=${keyword}${hash}`);
-    }
-  }
-
-  createSearchQuery(keyword) {
-    let query = keyword;
-
-    // pages included in specific path are not retrived when prefix is added
-    if (this.state.excludeTrashPages) {
-      query = `${query} -prefix:${specificPathNames.trash}`;
-    }
-    if (this.state.excludeUserPages) {
-      query = `${query} -prefix:${specificPathNames.user}`;
-    }
-
-    return query;
-  }
-
-  /**
-   * this method is called when user changes paging number
-   */
-  async onPagingNumberChanged(activePage) {
-    this.setState({ activePage }, () => this.search({ keyword: this.state.searchedKeyword }));
-  }
-
-  /**
-   * this method is called when user searches by pressing Enter or using searchbox
-   */
-  async onSearchInvoked(data) {
-    this.setState({ activePage: 1 }, () => this.search(data));
-  }
-
-  /**
-   * change number of pages to display per page and execute search method after.
-   */
-  async onPagingLimitChanged(limit) {
-    this.setState({ pagingLimit: limit }, () => this.search({ keyword: this.state.searchedKeyword }));
-  }
-
-  // todo: refactoring
-  // refs: https://redmine.weseek.co.jp/issues/82139
-  async search(data) {
-    // reset following states when search runs
-    this.setState({
-      selectedPagesIdList: new Set(),
-      selectAllCheckboxType: CheckboxType.NONE_CHECKED,
-    });
-
-    const keyword = data.keyword;
-    if (keyword === '') {
-      this.setState({
-        searchingKeyword: '',
-        searchedKeyword: '',
-        searchResults: [],
-        searchResultMeta: {},
-        searchResultCount: 0,
-        activePage: 1,
-      });
-
-      return true;
-    }
-
-    this.setState({
-      searchingKeyword: keyword,
-    });
-    const pagingLimit = this.state.pagingLimit;
-    const offset = (this.state.activePage * pagingLimit) - pagingLimit;
-    const { sort, order } = this.state;
-    try {
-      const res = await this.props.appContainer.apiGet('/search', {
-        q: this.createSearchQuery(keyword),
-        limit: pagingLimit,
-        offset,
-        sort,
-        order,
-      });
-
-      this.changeURL(keyword);
-      if (res.data.length > 0) {
-        this.setState({
-          searchedKeyword: keyword,
-          searchResults: res.data,
-          searchResultMeta: res.meta,
-          searchResultCount: res.meta.total,
-          focusedSearchResultData: res.data[0],
-          // reset active page if keyword changes, otherwise set the current state
-          activePage: this.state.searchedKeyword === keyword ? this.state.activePage : 1,
-        });
-      }
-      else {
-        this.setState({
-          searchedKeyword: keyword,
-          searchResults: [],
-          searchResultMeta: {},
-          searchResultCount: 0,
-          focusedSearchResultData: {},
-          activePage: 1,
-        });
-      }
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  selectPage= (pageId) => {
-    const index = this.state.searchResults.findIndex(({ pageData }) => {
-      return pageData._id === pageId;
-    });
-    this.setState({
-      focusedSearchResultData: this.state.searchResults[index],
-    });
-  }
-
-  toggleCheckBox = (pageId) => {
-    const { selectedPagesIdList } = this.state;
-
-    if (selectedPagesIdList.has(pageId)) {
-      selectedPagesIdList.delete(pageId);
-    }
-    else {
-      selectedPagesIdList.add(pageId);
-    }
-    switch (selectedPagesIdList.size) {
-      case 0:
-        return this.setState({ selectAllCheckboxType: CheckboxType.NONE_CHECKED });
-      case this.state.searchResults.length:
-        return this.setState({ selectAllCheckboxType: CheckboxType.ALL_CHECKED });
-      default:
-        return this.setState({ selectAllCheckboxType: CheckboxType.INDETERMINATE });
-    }
-  }
-
-  toggleAllCheckBox = (nextSelectAllCheckboxType) => {
-    const { selectedPagesIdList, searchResults } = this.state;
-    if (nextSelectAllCheckboxType === CheckboxType.NONE_CHECKED) {
-      selectedPagesIdList.clear();
-    }
-    else {
-      searchResults.forEach((page) => {
-        selectedPagesIdList.add(page.pageData._id);
-      });
-    }
-    this.setState({
-      selectedPagesIdList,
-      selectAllCheckboxType: nextSelectAllCheckboxType,
-    });
-  };
-
-  getSelectedPagesToDelete() {
-    const filteredPages = this.state.searchResults.filter((page) => {
-      return Array.from(this.state.deleteTargetPageIds).find(id => id === page.pageData._id);
-    });
-    return filteredPages.map(page => ({
-      pageId: page.pageData._id,
-      revisionId: page.pageData.revision,
-      path: page.pageData.path,
-    }));
-  }
-
-  deleteSinglePageButtonHandler(pageId) {
-    this.setState({ deleteTargetPageIds: new Set([pageId]) });
-    this.setState({ isDeleteConfirmModalShown: true });
-  }
-
-  deleteAllPagesButtonHandler() {
-    if (this.state.selectedPagesIdList.size === 0) { return }
-    this.setState({ deleteTargetPageIds: this.state.selectedPagesIdList });
-    this.setState({ isDeleteConfirmModalShown: true });
-  }
-
-  closeDeleteConfirmModalHandler() {
-    this.setState({ isDeleteConfirmModalShown: false });
-  }
-
-  renderSearchResultContent = () => {
-    return (
-      <SearchResultContent
-        appContainer={this.props.appContainer}
-        searchingKeyword={this.state.searchingKeyword}
-        focusedSearchResultData={this.state.focusedSearchResultData}
-        showPageControlDropdown={!this.props.isGuestUser}
-      >
-      </SearchResultContent>
-    );
-  }
-
-  renderSearchResultList = () => {
-    return (
-      <SearchResultList
-        pages={this.state.searchResults || []}
-        isEnableActions={!this.props.isGuestUser}
-        focusedSearchResultData={this.state.focusedSearchResultData}
-        selectedPagesIdList={this.state.selectedPagesIdList || []}
-        searchResultCount={this.state.searchResultCount}
-        activePage={this.state.activePage}
-        pagingLimit={this.state.pagingLimit}
-        onClickItem={this.selectPage}
-        onClickCheckbox={this.toggleCheckBox}
-        onPagingNumberChanged={this.onPagingNumberChanged}
-        onClickDeleteButton={this.deleteSinglePageButtonHandler}
-      />
-    );
-  }
-
-  renderSearchControl = () => {
-    return (
-      <SearchControl
-        searchingKeyword={this.state.searchingKeyword}
-        sort={this.state.sort}
-        order={this.state.order}
-        searchResultCount={this.state.searchResultCount || 0}
-        appContainer={this.props.appContainer}
-        onSearchInvoked={this.onSearchInvoked}
-        onClickSelectAllCheckbox={this.toggleAllCheckBox}
-        selectAllCheckboxType={this.state.selectAllCheckboxType}
-        onClickDeleteAllButton={this.deleteAllPagesButtonHandler}
-        onExcludeUserPagesSwitched={this.switchExcludeUserPagesHandler}
-        onExcludeTrashPagesSwitched={this.switchExcludeTrashPagesHandler}
-        excludeUserPages={this.state.excludeUserPages}
-        excludeTrashPages={this.state.excludeTrashPages}
-        onChangeSortInvoked={this.onChangeSortInvoked}
-      >
-      </SearchControl>
-    );
-  }
-
-  render() {
-    return (
-      <div>
-        <SearchPageLayout
-          SearchControl={this.renderSearchControl}
-          SearchResultList={this.renderSearchResultList}
-          SearchResultContent={this.renderSearchResultContent}
-          searchResultMeta={this.state.searchResultMeta}
-          searchingKeyword={this.state.searchedKeyword}
-          onPagingLimitChanged={this.onPagingLimitChanged}
-          pagingLimit={this.state.pagingLimit}
-          activePage={this.state.activePage}
-        >
-        </SearchPageLayout>
-        {/* TODO: show PageDeleteModal with usePageDeleteModal by 87569  */}
-        <PageDeleteModal
-          isOpen={this.state.isDeleteConfirmModalShown}
-          onClose={this.closeDeleteConfirmModalHandler}
-          pages={this.getSelectedPagesToDelete()}
-        />
-      </div>
-    );
-  }
-
-}
-
-/**
- * Wrapper component for using unstated
- */
-const SearchPageHOCWrapper = withTranslation()(withUnstatedContainers(SearchPage, [AppContainer]));
-
-SearchPage.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  query: PropTypes.object,
-  isGuestUser: PropTypes.bool.isRequired,
-};
-SearchPage.defaultProps = {
-  // pollInterval: 1000,
-  query: SearchPage.getQueryByLocation(window.location || {}),
-};
-
-const SearchPageFCWrapper = (props) => {
-  const { data: isGuestUser } = useIsGuestUser();
-
-  /*
-   * dependencies
-   */
-  if (isGuestUser == null) {
-    return null;
-  }
-
-  return <SearchPageHOCWrapper {...props} isGuestUser={isGuestUser} />;
-};
-
-export default SearchPageFCWrapper;

+ 260 - 0
packages/app/src/components/SearchPage.tsx

@@ -0,0 +1,260 @@
+import React, {
+  useCallback, useEffect, useMemo, useRef, useState,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { parse as parseQuerystring } from 'querystring';
+
+import AppContainer from '~/client/services/AppContainer';
+import { IFormattedSearchResult } from '~/interfaces/search';
+import { ISelectableAll, ISelectableAndIndeterminatable } from '~/client/interfaces/selectable-all';
+import { ISearchConditions, ISearchConfigurations, useSWRxFullTextSearch } from '~/stores/search';
+
+import PaginationWrapper from './PaginationWrapper';
+import { OperateAllControl } from './SearchPage/OperateAllControl';
+import SearchControl from './SearchPage/SearchControl';
+
+import { SearchPageBase } from './SearchPage2/SearchPageBase';
+
+
+// TODO: replace with "customize:showPageLimitationS"
+const INITIAL_PAGIONG_SIZE = 20;
+
+
+/**
+ * SearchResultListHead
+ */
+
+type SearchResultListHeadProps = {
+  searchResult: IFormattedSearchResult,
+  searchingKeyword: string,
+  offset: number,
+  pagingSize: number,
+  onPagingSizeChanged: (size: number) => void,
+}
+
+const SearchResultListHead = React.memo((props: SearchResultListHeadProps): JSX.Element => {
+  const { t } = useTranslation();
+
+  const {
+    searchResult, searchingKeyword, offset, pagingSize,
+    onPagingSizeChanged,
+  } = props;
+
+  const { took, total, hitsCount } = searchResult.meta;
+  const leftNum = offset + 1;
+  const rightNum = offset + hitsCount;
+
+  return (
+    <div className="d-flex align-items-center justify-content-between">
+      <div className="text-nowrap">
+        {t('search_result.result_meta')}
+        <span className="search-result-keyword">{`"${searchingKeyword}"`}</span>
+        <span className="ml-3">{`${leftNum}-${rightNum}`} / {total}</span>
+        { took != null && (
+          <span className="ml-3 text-muted">({took}ms)</span>
+        ) }
+      </div>
+      <div className="input-group search-result-select-group ml-4 d-lg-flex d-none">
+        <div className="input-group-prepend">
+          <label className="input-group-text text-muted" htmlFor="inputGroupSelect01">{t('search_result.number_of_list_to_display')}</label>
+        </div>
+        <select
+          defaultValue={pagingSize}
+          className="custom-select"
+          id="inputGroupSelect01"
+          onChange={e => onPagingSizeChanged(Number(e.target.value))}
+        >
+          {[20, 50, 100, 200].map((limit) => {
+            return <option key={limit} value={limit}>{limit} {t('search_result.page_number_unit')}</option>;
+          })}
+        </select>
+      </div>
+    </div>
+  );
+});
+
+
+/**
+ * SearchPage
+ */
+
+const getParsedUrlQuery = () => {
+  const search = window.location.search || '?';
+  return parseQuerystring(search.slice(1)); // remove heading '?' and parse
+};
+
+type Props = {
+  appContainer: AppContainer,
+}
+
+export const SearchPage = (props: Props): JSX.Element => {
+  const { t } = useTranslation();
+
+  const {
+    appContainer,
+  } = props;
+
+  // parse URL Query
+  const parsedQueries = getParsedUrlQuery().q;
+  const initQ = (Array.isArray(parsedQueries) ? parsedQueries.join(' ') : parsedQueries) ?? '';
+
+  const [keyword, setKeyword] = useState<string>(initQ);
+  const [configurationsByControl, setConfigurationsByControl] = useState<Partial<ISearchConfigurations>>({
+  });
+  const [configurationsByPagination, setConfigurationsByPagination] = useState<Partial<ISearchConfigurations>>({
+    limit: INITIAL_PAGIONG_SIZE,
+  });
+
+  const selectAllControlRef = useRef<ISelectableAndIndeterminatable|null>(null);
+  const searchPageBaseRef = useRef<ISelectableAll|null>(null);
+
+  const { data, conditions } = useSWRxFullTextSearch(keyword, {
+    limit: INITIAL_PAGIONG_SIZE,
+    ...configurationsByControl,
+    ...configurationsByPagination,
+  });
+
+  const searchInvokedHandler = useCallback((_keyword: string, newConfigurations: Partial<ISearchConfigurations>) => {
+    setKeyword(_keyword);
+    setConfigurationsByControl(newConfigurations);
+  }, []);
+
+  const selectAllCheckboxChangedHandler = useCallback((isChecked: boolean) => {
+    const instance = searchPageBaseRef.current;
+
+    if (instance == null) {
+      return;
+    }
+
+    if (isChecked) {
+      instance.selectAll();
+    }
+    else {
+      instance.deselectAll();
+    }
+  }, []);
+
+  const selectedPagesByCheckboxesChangedHandler = useCallback((selectedCount: number, totalCount: number) => {
+    const instance = selectAllControlRef.current;
+
+    if (instance == null) {
+      return;
+    }
+
+    if (selectedCount === 0) {
+      instance.deselect();
+    }
+    else if (selectedCount === totalCount) {
+      instance.select();
+    }
+    else {
+      instance.setIndeterminate();
+    }
+  }, []);
+
+  const pagingNumberChangedHandler = useCallback((activePage: number) => {
+    const currentLimit = configurationsByPagination.limit ?? INITIAL_PAGIONG_SIZE;
+    setConfigurationsByPagination({
+      ...configurationsByPagination,
+      offset: (activePage - 1) * currentLimit,
+    });
+  }, [configurationsByPagination]);
+
+  const initialSearchConditions: Partial<ISearchConditions> = useMemo(() => {
+    return {
+      keyword: initQ,
+      limit: INITIAL_PAGIONG_SIZE,
+    };
+  }, [initQ]);
+
+  // push state
+  useEffect(() => {
+    const newUrl = new URL('/_search', 'http://example.com');
+    newUrl.searchParams.append('q', keyword);
+    window.history.pushState('', `Search - ${keyword}`, `${newUrl.pathname}${newUrl.search}`);
+  }, [keyword]);
+  const hitsCount = data?.meta.hitsCount;
+
+  const { offset, limit } = conditions;
+
+  const deleteAllControl = useMemo(() => {
+    const isDisabled = hitsCount === 0;
+
+    return (
+      <OperateAllControl
+        ref={selectAllControlRef}
+        isCheckboxDisabled={isDisabled}
+        onCheckboxChanged={selectAllCheckboxChangedHandler}
+      >
+        <button
+          type="button"
+          className="btn btn-outline-danger border-0 px-2"
+          disabled={isDisabled}
+          onClick={() => null /* TODO implement */}
+        >
+          <i className="icon-fw icon-trash"></i>
+          {t('search_result.delete_all_selected_page')}
+        </button>
+      </OperateAllControl>
+    );
+  }, [hitsCount, selectAllCheckboxChangedHandler, t]);
+
+  const searchControl = useMemo(() => {
+    return (
+      <SearchControl
+        initialSearchConditions={initialSearchConditions}
+        onSearchInvoked={searchInvokedHandler}
+        deleteAllControl={deleteAllControl}
+      >
+      </SearchControl>
+    );
+  }, [deleteAllControl, initialSearchConditions, searchInvokedHandler]);
+
+  const searchResultListHead = useMemo(() => {
+    if (data == null) {
+      return <></>;
+    }
+    return (
+      <SearchResultListHead
+        searchResult={data}
+        searchingKeyword={keyword}
+        offset={offset}
+        pagingSize={limit}
+        onPagingSizeChanged={() => {}}
+      />
+    );
+  }, [data, keyword, limit, offset]);
+
+  const searchPager = useMemo(() => {
+    // when pager is not needed
+    if (data == null || data.meta.hitsCount === data.meta.total) {
+      return <></>;
+    }
+
+    const { total } = data.meta;
+    const { offset, limit } = conditions;
+
+    return (
+      <PaginationWrapper
+        activePage={Math.floor(offset / limit) + 1}
+        totalItemsCount={total}
+        pagingLimit={configurationsByPagination?.limit}
+        changePage={pagingNumberChangedHandler}
+      />
+    );
+  }, [conditions, configurationsByPagination?.limit, data, pagingNumberChangedHandler]);
+
+  return (
+    <SearchPageBase
+      ref={searchPageBaseRef}
+      appContainer={appContainer}
+      pages={data?.data}
+      onSelectedPagesByCheckboxesChanged={selectedPagesByCheckboxesChangedHandler}
+      // Components
+      searchControl={searchControl}
+      searchResultListHead={searchResultListHead}
+      searchPager={searchPager}
+    />
+  );
+};

+ 0 - 64
packages/app/src/components/SearchPage/DeleteSelectedPageGroup.tsx

@@ -1,64 +0,0 @@
-import React, { FC, useEffect, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-import { IndeterminateInputElement } from '~/interfaces/indeterminate-input-elm';
-import { CheckboxType } from '../../interfaces/search';
-
-type Props = {
-  isSelectAllCheckboxDisabled: boolean,
-  selectAllCheckboxType: CheckboxType,
-  onClickDeleteAllButton?: () => void,
-  onClickSelectAllCheckbox?: (nextSelectAllCheckboxType: CheckboxType) => void,
-}
-
-const DeleteSelectedPageGroup:FC<Props> = (props:Props) => {
-  const { t } = useTranslation();
-  const {
-    onClickDeleteAllButton, onClickSelectAllCheckbox, selectAllCheckboxType,
-  } = props;
-
-  const onClickCheckbox = () => {
-    if (onClickSelectAllCheckbox != null) {
-      const next = selectAllCheckboxType === CheckboxType.ALL_CHECKED ? CheckboxType.NONE_CHECKED : CheckboxType.ALL_CHECKED;
-      onClickSelectAllCheckbox(next);
-    }
-  };
-
-  const onClickDeleteButton = () => {
-    if (onClickDeleteAllButton != null) { onClickDeleteAllButton() }
-  };
-
-  const selectAllCheckboxElm = useRef<IndeterminateInputElement>(null);
-  useEffect(() => {
-    if (selectAllCheckboxElm.current != null) {
-      selectAllCheckboxElm.current.indeterminate = selectAllCheckboxType === CheckboxType.INDETERMINATE;
-    }
-  }, [selectAllCheckboxType]);
-
-  return (
-
-    <div className="d-flex align-items-center">
-      <input
-        id="check-all-pages"
-        type="checkbox"
-        name="check-all-pages"
-        className="grw-indeterminate-checkbox"
-        ref={selectAllCheckboxElm}
-        disabled={props.isSelectAllCheckboxDisabled}
-        onClick={onClickCheckbox}
-        checked={selectAllCheckboxType === CheckboxType.ALL_CHECKED}
-      />
-      <button
-        type="button"
-        className="btn text-danger font-weight-light p-0 ml-2"
-        disabled={selectAllCheckboxType === CheckboxType.NONE_CHECKED}
-        onClick={onClickDeleteButton}
-      >
-        <i className="icon-trash"></i>
-        {t('search_result.delete_all_selected_page')}
-      </button>
-    </div>
-  );
-
-};
-
-export default DeleteSelectedPageGroup;

+ 0 - 42
packages/app/src/components/SearchPage/IncludeSpecificPathButton.jsx

@@ -1,42 +0,0 @@
-import React, { useState } from 'react';
-import PropTypes from 'prop-types';
-import { useTranslation } from 'react-i18next';
-
-const IncludeSpecificPathButton = (props) => {
-  const { pathToInclude, checked } = props;
-  const { t } = useTranslation();
-
-  // TODO : implement this function
-  // 77526 story https://estoc.weseek.co.jp/redmine/issues/77526
-  // 77535 stroy https://estoc.weseek.co.jp/redmine/issues/77535
-  function includeSpecificPathInSearchResult(pathToInclude) {
-    console.log(`now including ${pathToInclude} in search result`);
-  }
-  return (
-    <div className="border px-2 btn btn-outline-secondary">
-      <label className="mb-0">
-        <span className="font-weight-light">
-          {pathToInclude === '/user'
-            ? t('search_result.include_certain_path', { pathToInclude: '/user' }) : t('search_result.include_certain_path', { pathToInclude: '/trash' })}
-        </span>
-        <input
-          type="checkbox"
-          name="check-include-specific-path"
-          onChange={() => {
-            if (checked) {
-              includeSpecificPathInSearchResult(pathToInclude);
-            }
-          }}
-        />
-      </label>
-    </div>
-  );
-
-};
-
-IncludeSpecificPathButton.propTypes = {
-  pathToInclude: PropTypes.string.isRequired,
-  checked: PropTypes.bool.isRequired,
-};
-
-export default IncludeSpecificPathButton;

+ 74 - 0
packages/app/src/components/SearchPage/OperateAllControl.tsx

@@ -0,0 +1,74 @@
+import React, {
+  ChangeEvent, forwardRef, ForwardRefRenderFunction, useImperativeHandle, useRef,
+} from 'react';
+import { CustomInput } from 'reactstrap';
+import { ISelectableAndIndeterminatable } from '~/client/interfaces/selectable-all';
+import { IndeterminateInputElement } from '~/interfaces/indeterminate-input-elm';
+
+type Props = {
+  isCheckboxDisabled?: boolean,
+  onCheckboxChanged?: (isChecked: boolean) => void,
+
+  children?: React.ReactNode,
+}
+
+const OperateAllControlSubstance: ForwardRefRenderFunction<ISelectableAndIndeterminatable, Props> = (props: Props, ref): JSX.Element => {
+  const {
+    isCheckboxDisabled,
+    onCheckboxChanged,
+
+    children,
+  } = props;
+
+  const selectAllCheckboxElm = useRef<IndeterminateInputElement>(null);
+
+  // publish ISelectable methods
+  useImperativeHandle(ref, () => ({
+    select: () => {
+      const input = selectAllCheckboxElm.current;
+      if (input != null) {
+        input.checked = true;
+        input.indeterminate = false;
+      }
+    },
+    deselect: () => {
+      const input = selectAllCheckboxElm.current;
+      if (input != null) {
+        input.checked = false;
+        input.indeterminate = false;
+      }
+    },
+    setIndeterminate: () => {
+      const input = selectAllCheckboxElm.current;
+      if (input != null) {
+        input.indeterminate = true;
+      }
+    },
+  }));
+
+  const checkboxChangedHandler = (e: ChangeEvent<HTMLInputElement>) => {
+    if (onCheckboxChanged != null) {
+      onCheckboxChanged(e.target.checked);
+    }
+  };
+
+  return (
+
+    <div className="d-flex align-items-center">
+      <CustomInput
+        type="checkbox"
+        id="cb-check-all"
+        data-testid="cb-select-all"
+        innerRef={selectAllCheckboxElm}
+        disabled={isCheckboxDisabled}
+        onChange={checkboxChangedHandler}
+      />
+      <span className="ml-2">
+        {children}
+      </span>
+    </div>
+  );
+
+};
+
+export const OperateAllControl = React.memo(forwardRef(OperateAllControlSubstance));

+ 72 - 91
packages/app/src/components/SearchPage/SearchControl.tsx

@@ -1,131 +1,101 @@
-import React, { FC, useState } from 'react';
+import React, {
+  FC, useCallback, useEffect, useState,
+} from 'react';
 import { useTranslation } from 'react-i18next';
+
+import { SORT_AXIS, SORT_ORDER } from '~/interfaces/search';
+import { ISearchConditions, ISearchConfigurations } from '~/stores/search';
+
 import SearchPageForm from './SearchPageForm';
-import AppContainer from '../../client/services/AppContainer';
-import DeleteSelectedPageGroup from './DeleteSelectedPageGroup';
 import SearchOptionModal from './SearchOptionModal';
 import SortControl from './SortControl';
-import { CheckboxType, SORT_AXIS, SORT_ORDER } from '../../interfaces/search';
 
 type Props = {
-  searchingKeyword: string,
-  sort: SORT_AXIS,
-  order: SORT_ORDER,
-  appContainer: AppContainer,
-  searchResultCount: number,
-  selectAllCheckboxType: CheckboxType,
-  onClickDeleteAllButton?: () => void
-  onClickSelectAllCheckbox?: (nextSelectAllCheckboxType: CheckboxType) => void,
-  excludeUserPages: boolean,
-  excludeTrashPages: boolean,
-  onSearchInvoked: (data: {keyword: string}) => boolean,
-  onExcludeUserPagesSwitched?: () => void,
-  onExcludeTrashPagesSwitched?: () => void,
-  onChangeSortInvoked?: (nextSort: SORT_AXIS, nextOrder: SORT_ORDER) => void,
+  initialSearchConditions: Partial<ISearchConditions>,
+
+  onSearchInvoked: (keyword: string, configurations: Partial<ISearchConfigurations>) => void,
+
+  deleteAllControl: React.ReactNode,
 }
 
-const SearchControl: FC <Props> = (props: Props) => {
+const SearchControl: FC <Props> = React.memo((props: Props) => {
+
+  const {
+    initialSearchConditions,
+    onSearchInvoked,
+    deleteAllControl,
+  } = props;
 
+  const [keyword, setKeyword] = useState(initialSearchConditions.keyword ?? '');
+  const [sort, setSort] = useState<SORT_AXIS>(initialSearchConditions.sort ?? SORT_AXIS.RELATION_SCORE);
+  const [order, setOrder] = useState<SORT_ORDER>(initialSearchConditions.order ?? SORT_ORDER.DESC);
+  const [includeUserPages, setIncludeUserPages] = useState(initialSearchConditions.includeUserPages ?? false);
+  const [includeTrashPages, setIncludeTrashPages] = useState(initialSearchConditions.includeTrashPages ?? false);
   const [isFileterOptionModalShown, setIsFileterOptionModalShown] = useState(false);
-  // Temporaly workaround for lint error
-  // later needs to be fixed: SearchControl to typescript componet
-  const SearchPageFormTypeAny : any = SearchPageForm;
-  const { t } = useTranslation('');
-  const { searchResultCount } = props;
 
-  const switchExcludeUserPagesHandler = () => {
-    if (props.onExcludeUserPagesSwitched != null) {
-      props.onExcludeUserPagesSwitched();
-    }
-  };
+  const { t } = useTranslation('');
 
-  const switchExcludeTrashPagesHandler = () => {
-    if (props.onExcludeTrashPagesSwitched != null) {
-      props.onExcludeTrashPagesSwitched();
+  const invokeSearch = useCallback(() => {
+    if (onSearchInvoked == null) {
+      return;
     }
-  };
 
-  const onChangeSortInvoked = (nextSort: SORT_AXIS, nextOrder:SORT_ORDER) => {
-    if (props.onChangeSortInvoked != null) {
-      props.onChangeSortInvoked(nextSort, nextOrder);
-    }
-  };
+    onSearchInvoked(keyword, {
+      sort, order, includeUserPages, includeTrashPages,
+    });
+  }, [keyword, sort, order, includeTrashPages, includeUserPages, onSearchInvoked]);
 
-  const openSearchOptionModalHandler = () => {
-    setIsFileterOptionModalShown(true);
-  };
+  const searchFormChangedHandler = useCallback(({ keyword }) => {
+    setKeyword(keyword as string);
+  }, []);
 
-  const closeSearchOptionModalHandler = () => {
-    setIsFileterOptionModalShown(false);
-  };
+  const changeSortHandler = useCallback((nextSort: SORT_AXIS, nextOrder: SORT_ORDER) => {
+    setSort(nextSort);
+    setOrder(nextOrder);
+  }, []);
 
-  const onRetrySearchInvoked = () => {
-    if (props.onSearchInvoked != null) {
-      props.onSearchInvoked({ keyword: props.searchingKeyword });
-    }
-  };
-
-  const rednerSearchOptionModal = () => {
-    return (
-      <SearchOptionModal
-        isOpen={isFileterOptionModalShown || false}
-        onClickFilteringSearchResult={onRetrySearchInvoked}
-        onClose={closeSearchOptionModalHandler}
-        onExcludeUserPagesSwitched={switchExcludeUserPagesHandler}
-        onExcludeTrashPagesSwitched={switchExcludeTrashPagesHandler}
-        excludeUserPages={props.excludeUserPages}
-        excludeTrashPages={props.excludeTrashPages}
-      />
-    );
-  };
-
-  const renderSortControl = () => {
-    return (
-      <SortControl
-        sort={props.sort}
-        order={props.order}
-        onChangeSortInvoked={onChangeSortInvoked}
-      />
-    );
-  };
+  useEffect(() => {
+    invokeSearch();
+  }, [invokeSearch]);
 
   return (
     <div className="position-sticky fixed-top shadow-sm">
       <div className="grw-search-page-nav d-flex py-3 align-items-center">
         <div className="flex-grow-1 mx-4">
-          <SearchPageFormTypeAny
-            keyword={props.searchingKeyword}
-            appContainer={props.appContainer}
-            onSearchFormChanged={props.onSearchInvoked}
+          <SearchPageForm
+            keyword={keyword}
+            onSearchFormChanged={searchFormChangedHandler}
           />
         </div>
 
         {/* sort option: show when screen is larger than lg */}
         <div className="mr-4 d-lg-flex d-none">
-          {renderSortControl()}
+          <SortControl
+            sort={sort}
+            order={order}
+            onChange={changeSortHandler}
+          />
         </div>
       </div>
       {/* TODO: replace the following elements deleteAll button , relevance button and include specificPath button component */}
       <div className="search-control d-flex align-items-center py-md-2 py-3 px-md-4 px-3 border-bottom border-gray">
         <div className="d-flex pl-md-2">
-          {/* Todo: design will be fixed in #80324. Function will be implemented in #77525 */}
-          <DeleteSelectedPageGroup
-            isSelectAllCheckboxDisabled={searchResultCount === 0}
-            selectAllCheckboxType={props.selectAllCheckboxType}
-            onClickDeleteAllButton={props.onClickDeleteAllButton}
-            onClickSelectAllCheckbox={props.onClickSelectAllCheckbox}
-          />
+          {deleteAllControl}
         </div>
         {/* sort option: show when screen is smaller than lg */}
         <div className="mr-md-4 mr-2 d-flex d-lg-none ml-auto">
-          {renderSortControl()}
+          <SortControl
+            sort={sort}
+            order={order}
+            onChange={changeSortHandler}
+          />
         </div>
         {/* filter option */}
         <div className="d-lg-none">
           <button
             type="button"
             className="btn"
-            onClick={openSearchOptionModalHandler}
+            onClick={() => setIsFileterOptionModalShown(true)}
           >
             <i className="icon-equalizer"></i>
           </button>
@@ -138,7 +108,8 @@ const SearchControl: FC <Props> = (props: Props) => {
                   className="mr-2"
                   type="checkbox"
                   id="flexCheckDefault"
-                  onClick={switchExcludeUserPagesHandler}
+                  defaultChecked={includeUserPages}
+                  onChange={e => setIncludeUserPages(e.target.checked)}
                 />
                 {t('Include Subordinated Target Page', { target: '/user' })}
               </label>
@@ -151,7 +122,8 @@ const SearchControl: FC <Props> = (props: Props) => {
                   className="mr-2"
                   type="checkbox"
                   id="flexCheckChecked"
-                  onClick={switchExcludeTrashPagesHandler}
+                  defaultChecked={includeTrashPages}
+                  onChange={e => setIncludeTrashPages(e.target.checked)}
                 />
                 {t('Include Subordinated Target Page', { target: '/trash' })}
               </label>
@@ -159,10 +131,19 @@ const SearchControl: FC <Props> = (props: Props) => {
           </div>
         </div>
       </div>
-      {rednerSearchOptionModal()}
+
+      <SearchOptionModal
+        isOpen={isFileterOptionModalShown || false}
+        onClose={() => setIsFileterOptionModalShown(false)}
+        includeUserPages={includeUserPages}
+        includeTrashPages={includeTrashPages}
+        onIncludeUserPagesSwitched={setIncludeUserPages}
+        onIncludeTrashPagesSwitched={setIncludeTrashPages}
+      />
+
     </div>
   );
-};
+});
 
 
 export default SearchControl;

+ 22 - 23
packages/app/src/components/SearchPage/SearchOptionModal.tsx

@@ -2,18 +2,17 @@ import React, { FC } from 'react';
 import { useTranslation } from 'react-i18next';
 
 import {
-  Modal, ModalHeader, ModalBody, ModalFooter,
+  Modal, ModalHeader, ModalBody,
 } from 'reactstrap';
 
 
 type Props = {
   isOpen: boolean,
-  excludeUserPages: boolean,
-  excludeTrashPages: boolean,
+  includeUserPages: boolean,
+  includeTrashPages: boolean,
   onClose?: () => void,
-  onExcludeUserPagesSwitched?: () => void,
-  onExcludeTrashPagesSwitched?: () => void,
-  onClickFilteringSearchResult?: () => void,
+  onIncludeUserPagesSwitched?: (isChecked: boolean) => void,
+  onIncludeTrashPagesSwitched?: (isChecked: boolean) => void,
 }
 
 const SearchOptionModal: FC<Props> = (props: Props) => {
@@ -21,7 +20,10 @@ const SearchOptionModal: FC<Props> = (props: Props) => {
   const { t } = useTranslation('');
 
   const {
-    isOpen, onClose, excludeUserPages, excludeTrashPages,
+    isOpen, includeUserPages, includeTrashPages,
+    onClose,
+    onIncludeUserPagesSwitched,
+    onIncludeTrashPagesSwitched,
   } = props;
 
   const onCloseModal = () => {
@@ -30,10 +32,15 @@ const SearchOptionModal: FC<Props> = (props: Props) => {
     }
   };
 
-  const onClickFilteringSearchResult = () => {
-    if (props.onClickFilteringSearchResult != null) {
-      props.onClickFilteringSearchResult();
-      onCloseModal();
+  const includeUserPagesChangeHandler = (isChecked: boolean) => {
+    if (onIncludeUserPagesSwitched != null) {
+      onIncludeUserPagesSwitched(isChecked);
+    }
+  };
+
+  const includeTrashPagesChangeHandler = (isChecked: boolean) => {
+    if (onIncludeTrashPagesSwitched != null) {
+      onIncludeTrashPagesSwitched(isChecked);
     }
   };
 
@@ -49,8 +56,8 @@ const SearchOptionModal: FC<Props> = (props: Props) => {
               <input
                 className="mr-2"
                 type="checkbox"
-                onChange={props.onExcludeUserPagesSwitched}
-                checked={!excludeUserPages}
+                onChange={e => includeUserPagesChangeHandler(e.target.checked)}
+                checked={includeUserPages}
               />
               {t('Include Subordinated Target Page', { target: '/user' })}
             </label>
@@ -60,22 +67,14 @@ const SearchOptionModal: FC<Props> = (props: Props) => {
               <input
                 className="mr-2"
                 type="checkbox"
-                onChange={props.onExcludeTrashPagesSwitched}
-                checked={!excludeTrashPages}
+                onChange={e => includeTrashPagesChangeHandler(e.target.checked)}
+                checked={includeTrashPages}
               />
               {t('Include Subordinated Target Page', { target: '/trash' })}
             </label>
           </div>
         </div>
       </ModalBody>
-      <ModalFooter>
-        <button
-          type="button"
-          className="btn btn-secondary"
-          onClick={onClickFilteringSearchResult}
-        >{t('search_result.search_again')}
-        </button>
-      </ModalFooter>
     </Modal>
   );
 };

+ 0 - 79
packages/app/src/components/SearchPage/SearchPageLayout.tsx

@@ -1,79 +0,0 @@
-import React, { FC } from 'react';
-import { useTranslation } from 'react-i18next';
-
-type SearchResultMeta = {
-  took?: number,
-  total?: number,
-  results?: number
-}
-
-type Props = {
-  SearchControl: React.FunctionComponent,
-  SearchResultList: React.FunctionComponent,
-  SearchResultContent: React.FunctionComponent,
-  searchResultMeta: SearchResultMeta,
-  searchingKeyword: string,
-  pagingLimit: number,
-  activePage: number,
-  onPagingLimitChanged: (limit: number) => void
-}
-
-const SearchPageLayout: FC<Props> = (props: Props) => {
-  const { t } = useTranslation('');
-  const {
-    SearchResultList, SearchControl, SearchResultContent, searchResultMeta, searchingKeyword, pagingLimit, activePage,
-  } = props;
-
-  const renderShowingPageCountInfo = () => {
-    if (searchResultMeta.total == null || searchResultMeta.total === 0) return;
-    const leftNum = pagingLimit * (activePage - 1) + 1;
-    const rightNum = (leftNum - 1) + (searchResultMeta.results || 0);
-    return <span className="ml-3">{`${leftNum}-${rightNum}`} / {searchResultMeta.total || 0}</span>;
-  };
-
-  return (
-    <div className="content-main">
-      <div className="search-result d-flex" id="search-result">
-        <div className="mw-0 flex-grow-1 flex-basis-0 border boder-gray search-result-list" id="search-result-list">
-
-          <SearchControl></SearchControl>
-          <div className="search-result-list-scroll">
-            <div className="d-flex align-items-center justify-content-between my-3 ml-4">
-              <div className="search-result-meta text-nowrap">
-                <span className="font-weight-light">{t('search_result.result_meta')} </span>
-                <span className="h5">{`"${searchingKeyword}"`}</span>
-                {/* Todo: replace "1-10" to the appropriate value */}
-                {renderShowingPageCountInfo()}
-              </div>
-              <div className="input-group search-result-select-group ml-4 d-lg-flex d-none">
-                <div className="input-group-prepend">
-                  <label className="input-group-text text-muted" htmlFor="inputGroupSelect01">{t('search_result.number_of_list_to_display')}</label>
-                </div>
-                <select
-                  defaultValue={props.pagingLimit}
-                  className="custom-select"
-                  id="inputGroupSelect01"
-                  onChange={(e) => { props.onPagingLimitChanged(Number(e.target.value)) }}
-                >
-                  {[20, 50, 100, 200].map((limit) => {
-                    return <option key={limit} value={limit}>{limit}{t('search_result.page_number_unit')}</option>;
-                  })}
-                </select>
-              </div>
-            </div>
-
-            <div className="page-list px-md-4">
-              <SearchResultList></SearchResultList>
-            </div>
-          </div>
-        </div>
-        <div className="mw-0 flex-grow-1 flex-basis-0 d-none d-lg-block search-result-content">
-          <SearchResultContent></SearchResultContent>
-        </div>
-      </div>
-    </div>
-  );
-};
-
-
-export default SearchPageLayout;

+ 8 - 10
packages/app/src/components/SearchPage/SearchResultContent.tsx

@@ -48,8 +48,8 @@ const MUTATION_OBSERVER_CONFIG = { childList: true, subtree: true };
 
 type Props ={
   appContainer: AppContainer,
-  searchingKeyword:string,
-  focusedSearchResultData : IPageWithMeta<IPageSearchMeta>,
+  pageWithMeta : IPageWithMeta<IPageSearchMeta>,
+  highlightKeywords?: string[],
   showPageControlDropdown?: boolean,
 }
 
@@ -72,7 +72,7 @@ const generateObserverCallback = (doScroll: ()=>void) => {
   };
 };
 
-const SearchResultContent: FC<Props> = (props: Props) => {
+export const SearchResultContent: FC<Props> = (props: Props) => {
   const scrollElementRef = useRef(null);
 
   // ***************************  Auto Scroll  ***************************
@@ -94,7 +94,8 @@ const SearchResultContent: FC<Props> = (props: Props) => {
 
   const {
     appContainer,
-    focusedSearchResultData,
+    pageWithMeta,
+    highlightKeywords,
     showPageControlDropdown,
   } = props;
 
@@ -102,7 +103,7 @@ const SearchResultContent: FC<Props> = (props: Props) => {
   const { open: openRenameModal } = usePageRenameModal();
   const { open: openDeleteModal } = usePageDeleteModal();
 
-  const page = focusedSearchResultData?.pageData;
+  const page = pageWithMeta?.pageData;
 
   const growiRenderer = appContainer.getRenderer('searchresult');
 
@@ -146,7 +147,7 @@ const SearchResultContent: FC<Props> = (props: Props) => {
         </div>
       </>
     );
-  }, [page, showPageControlDropdown, renameItemClickedHandler, deleteItemClickedHandler]);
+  }, [page, showPageControlDropdown, duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler]);
 
   // return if page is null
   if (page == null) return <></>;
@@ -163,12 +164,9 @@ const SearchResultContent: FC<Props> = (props: Props) => {
           pageId={page._id}
           pagePath={page.path}
           revisionId={page.revision}
-          highlightKeywords={props.searchingKeyword}
+          highlightKeywords={highlightKeywords}
         />
       </div>
     </div>
   );
 };
-
-
-export default SearchResultContent;

+ 53 - 39
packages/app/src/components/SearchPage/SearchResultList.tsx

@@ -1,38 +1,65 @@
-import React, { FC } from 'react';
-import { IPageInfoForEntity, IPageWithMeta, isIPageInfoForListing } from '~/interfaces/page';
+import React, {
+  forwardRef,
+  ForwardRefRenderFunction, useCallback, useImperativeHandle, useRef,
+} from 'react';
+import { ISelectable, ISelectableAll } from '~/client/interfaces/selectable-all';
+import { IPageWithMeta, isIPageInfoForListing } from '~/interfaces/page';
 import { IPageSearchMeta } from '~/interfaces/search';
+import { useIsGuestUser } from '~/stores/context';
 import { useSWRxPageInfoForList } from '~/stores/page';
 
 import { PageListItemL } from '../PageList/PageListItemL';
-import PaginationWrapper from '../PaginationWrapper';
 
 
 type Props = {
-  pages: IPageWithMeta<IPageInfoForEntity & IPageSearchMeta>[],
-  selectedPagesIdList: Set<string>
-  isEnableActions: boolean,
-  searchResultCount?: number,
-  activePage?: number,
-  pagingLimit?: number,
-  focusedSearchResultData?: IPageWithMeta<IPageSearchMeta>,
-  onPagingNumberChanged?: (activePage: number) => void,
-  onClickItem?: (pageId: string) => void,
-  onClickCheckbox?: (pageId: string) => void,
-  onClickInvoked?: (pageId: string) => void,
-  onClickDeleteButton?: (pageId: string) => void,
+  pages: IPageWithMeta<IPageSearchMeta>[],
+  selectedPageId?: string,
+  onPageSelected?: (page?: IPageWithMeta<IPageSearchMeta>) => void,
+  onCheckboxChanged?: (isChecked: boolean, pageId: string) => void,
 }
 
-const SearchResultList: FC<Props> = (props:Props) => {
+const SearchResultListSubstance: ForwardRefRenderFunction<ISelectableAll, Props> = (props:Props, ref) => {
   const {
-    pages, focusedSearchResultData, selectedPagesIdList, isEnableActions,
+    pages, selectedPageId,
+    onPageSelected,
   } = props;
 
   const pageIdsWithNoSnippet = pages
     .filter(page => (page.pageMeta?.elasticSearchResult?.snippet.length ?? 0) === 0)
     .map(page => page.pageData._id);
 
+  const { data: isGuestUser } = useIsGuestUser();
   const { data: idToPageInfo } = useSWRxPageInfoForList(pageIdsWithNoSnippet);
 
+  const itemsRef = useRef<(ISelectable|null)[]>([]);
+
+  // publish selectAll()
+  useImperativeHandle(ref, () => ({
+    selectAll: () => {
+      const items = itemsRef.current;
+      if (items != null) {
+        items.forEach(item => item != null && item.select());
+      }
+    },
+    deselectAll: () => {
+      const items = itemsRef.current;
+      if (items != null) {
+        items.forEach(item => item != null && item.deselect());
+      }
+    },
+  }));
+
+  const clickItemHandler = useCallback((pageId: string) => {
+    if (onPageSelected != null) {
+      const selectedPage = pages.find(page => page.pageData._id === pageId);
+      onPageSelected(selectedPage);
+    }
+  }, [onPageSelected, pages]);
+
+  const clickDeleteButtonHandler = useCallback((pageId: string) => {
+    // TODO implement
+  }, []);
+
   let injectedPage;
   // inject data to list
   if (idToPageInfo != null) {
@@ -54,39 +81,26 @@ const SearchResultList: FC<Props> = (props:Props) => {
     });
   }
 
-  const focusedPageId = (focusedSearchResultData != null && focusedSearchResultData.pageData != null) ? focusedSearchResultData.pageData._id : '';
   return (
     <ul className="page-list-ul list-group list-group-flush">
-      { (injectedPage ?? pages).map((page) => {
-        const isChecked = selectedPagesIdList.has(page.pageData._id);
-
+      { (injectedPage ?? pages).map((page, i) => {
         return (
           <PageListItemL
             key={page.pageData._id}
+            // eslint-disable-next-line no-return-assign
+            ref={c => itemsRef.current[i] = c}
             page={page}
-            isEnableActions={isEnableActions}
-            onClickItem={props.onClickItem}
-            onClickCheckbox={props.onClickCheckbox}
-            isChecked={isChecked}
-            isSelected={page.pageData._id === focusedPageId || false}
-            onClickDeleteButton={props.onClickDeleteButton}
+            isEnableActions={isGuestUser}
+            isSelected={page.pageData._id === selectedPageId}
+            onClickItem={clickItemHandler}
+            onCheckboxChanged={props.onCheckboxChanged}
+            onClickDeleteButton={clickDeleteButtonHandler}
           />
         );
       })}
-      {props.searchResultCount != null && props.searchResultCount > 0 && (
-        <div className="my-4 mx-auto">
-          <PaginationWrapper
-            activePage={props.activePage || 1}
-            changePage={props.onPagingNumberChanged}
-            totalItemsCount={props.searchResultCount || 0}
-            pagingLimit={props.pagingLimit}
-          />
-        </div>
-      )}
-
     </ul>
   );
 
 };
 
-export default SearchResultList;
+export const SearchResultList = forwardRef(SearchResultListSubstance);

+ 9 - 7
packages/app/src/components/SearchPage/SortControl.tsx

@@ -7,20 +7,22 @@ const { DESC, ASC } = SORT_ORDER;
 type Props = {
   sort: SORT_AXIS,
   order: SORT_ORDER,
-  onChangeSortInvoked?: (nextSort: SORT_AXIS, nextOrder: SORT_ORDER) => void,
+  onChange?: (nextSort: SORT_AXIS, nextOrder: SORT_ORDER) => void,
 }
 
 const SortControl: FC <Props> = (props: Props) => {
 
   const { t } = useTranslation('');
 
+  const { sort, order, onChange } = props;
+
   const onClickChangeSort = (nextSortAxis: SORT_AXIS, nextSortOrder: SORT_ORDER) => {
-    if (props.onChangeSortInvoked != null) {
-      props.onChangeSortInvoked(nextSortAxis, nextSortOrder);
+    if (onChange != null) {
+      onChange(nextSortAxis, nextSortOrder);
     }
   };
 
-  const renderOrderIcon = (order: SORT_ORDER) => {
+  const renderOrderIcon = () => {
     const iconClassName = ASC === order ? 'fa fa-sort-amount-asc' : 'fa fa-sort-amount-desc';
     return <i className={iconClassName} aria-hidden="true" />;
   };
@@ -30,7 +32,7 @@ const SortControl: FC <Props> = (props: Props) => {
       <div className="input-group">
         <div className="input-group-prepend">
           <div className="input-group-text border text-muted" id="btnGroupAddon">
-            {renderOrderIcon(props.order)}
+            {renderOrderIcon()}
           </div>
         </div>
         <div className="border rounded-right">
@@ -39,11 +41,11 @@ const SortControl: FC <Props> = (props: Props) => {
             className="btn dropdown-toggle search-sort-option-btn"
             data-toggle="dropdown"
           >
-            <span className="mr-4 text-secondary">{t(`search_result.sort_axis.${props.sort}`)}</span>
+            <span className="mr-4 text-secondary">{t(`search_result.sort_axis.${sort}`)}</span>
           </button>
           <div className="dropdown-menu dropdown-menu-right">
             {Object.values(SORT_AXIS).map((sortAxis) => {
-              const nextOrder = (props.sort !== sortAxis || props.order === ASC) ? DESC : ASC;
+              const nextOrder = (sort !== sortAxis || order === ASC) ? DESC : ASC;
               return (
                 <button
                   key={sortAxis}

+ 166 - 0
packages/app/src/components/SearchPage2/SearchPageBase.tsx

@@ -0,0 +1,166 @@
+import React, {
+  forwardRef, ForwardRefRenderFunction, useEffect, useImperativeHandle, useRef, useState,
+} from 'react';
+import { ISelectableAll } from '~/client/interfaces/selectable-all';
+import AppContainer from '~/client/services/AppContainer';
+import { IPageWithMeta } from '~/interfaces/page';
+import { IPageSearchMeta } from '~/interfaces/search';
+import { useIsGuestUser } from '~/stores/context';
+
+import { SearchResultContent } from '../SearchPage/SearchResultContent';
+import { SearchResultList } from '../SearchPage/SearchResultList';
+
+type Props = {
+  appContainer: AppContainer,
+
+  pages?: IPageWithMeta<IPageSearchMeta>[],
+
+  onSelectedPagesByCheckboxesChanged?: (selectedCount: number, totalCount: number) => void,
+
+  searchControl: React.ReactNode,
+  searchResultListHead: React.ReactNode,
+  searchPager: React.ReactNode,
+}
+
+const SearchPageBaseSubstance: ForwardRefRenderFunction<ISelectableAll, Props> = (props:Props, ref) => {
+  const {
+    appContainer,
+    pages,
+    onSelectedPagesByCheckboxesChanged,
+    searchControl, searchResultListHead, searchPager,
+  } = props;
+
+  const searchResultListRef = useRef<ISelectableAll|null>(null);
+
+  const { data: isGuestUser } = useIsGuestUser();
+
+  // TODO get search keywords and split
+  // ref: RevisionRenderer
+  //   [...keywords.match(/"[^"]+"|[^\u{20}\u{3000}]+/ug)].forEach((keyword, i) => {
+  const [highlightKeywords, setHightlightKeywords] = useState<string[]>([]);
+  const [selectedPageIdsByCheckboxes] = useState<Set<string>>(new Set());
+  // const [allPageIds] = useState<Set<string>>(new Set());
+  const [selectedPageWithMeta, setSelectedPageWithMeta] = useState<IPageWithMeta<IPageSearchMeta> | undefined>();
+
+  // publish selectAll()
+  useImperativeHandle(ref, () => ({
+    selectAll: () => {
+      const instance = searchResultListRef.current;
+      if (instance != null) {
+        instance.selectAll();
+      }
+
+      if (pages != null) {
+        pages.forEach(page => selectedPageIdsByCheckboxes.add(page.pageData._id));
+      }
+    },
+    deselectAll: () => {
+      const instance = searchResultListRef.current;
+      if (instance != null) {
+        instance.deselectAll();
+      }
+
+      selectedPageIdsByCheckboxes.clear();
+    },
+  }));
+
+  const checkboxChangedHandler = (isChecked: boolean, pageId: string) => {
+    if (pages == null || pages.length === 0) {
+      return;
+    }
+
+    if (isChecked) {
+      selectedPageIdsByCheckboxes.add(pageId);
+    }
+    else {
+      selectedPageIdsByCheckboxes.delete(pageId);
+    }
+
+    if (onSelectedPagesByCheckboxesChanged != null) {
+      onSelectedPagesByCheckboxesChanged(selectedPageIdsByCheckboxes.size, pages.length);
+    }
+  };
+
+  // select first item on load
+  useEffect(() => {
+    if (selectedPageWithMeta == null && pages != null && pages.length > 0) {
+      setSelectedPageWithMeta(pages[0]);
+    }
+  }, [pages, selectedPageWithMeta]);
+
+  // reset selectedPageIdsByCheckboxes
+  useEffect(() => {
+    if (pages == null) {
+      return;
+    }
+
+    if (pages.length > 0) {
+      selectedPageIdsByCheckboxes.clear();
+    }
+
+    if (onSelectedPagesByCheckboxesChanged != null) {
+      onSelectedPagesByCheckboxesChanged(selectedPageIdsByCheckboxes.size, pages.length);
+    }
+  }, [onSelectedPagesByCheckboxesChanged, pages, selectedPageIdsByCheckboxes]);
+
+  const isLoading = pages == null;
+
+  return (
+    <div className="content-main">
+      <div className="search-result d-flex" id="search-result">
+
+        <div className="mw-0 flex-grow-1 flex-basis-0 border boder-gray search-result-list" id="search-result-list">
+
+          {searchControl}
+
+          <div className="search-result-list-scroll">
+
+            { isLoading && (
+              <div className="mw-0 flex-grow-1 flex-basis-0 m-5 text-muted text-center">
+                <i className="fa fa-2x fa-spinner fa-pulse mr-1"></i>
+              </div>
+            ) }
+
+            { !isLoading && (
+              <>
+                <div className="my-3 px-md-4">
+                  {searchResultListHead}
+                </div>
+                <div className="page-list px-md-4">
+                  <SearchResultList
+                    ref={searchResultListRef}
+                    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+                    pages={pages!}
+                    selectedPageId={selectedPageWithMeta?.pageData._id}
+                    onPageSelected={page => setSelectedPageWithMeta(page)}
+                    onCheckboxChanged={checkboxChangedHandler}
+                  />
+                </div>
+                <div className="my-4 d-flex justify-content-center">
+                  {searchPager}
+                </div>
+              </>
+            ) }
+
+          </div>
+
+        </div>
+
+        <div className="mw-0 flex-grow-1 flex-basis-0 d-none d-lg-block search-result-content">
+          { selectedPageWithMeta != null && (
+            <SearchResultContent
+              appContainer={appContainer}
+              pageWithMeta={selectedPageWithMeta}
+              highlightKeywords={highlightKeywords}
+              showPageControlDropdown={isGuestUser}
+            />
+          )}
+        </div>
+
+      </div>
+    </div>
+  );
+};
+
+
+export const SearchPageBase = forwardRef(SearchPageBaseSubstance);

+ 31 - 5
packages/app/src/components/Sidebar/PageTree/Item.tsx

@@ -8,13 +8,13 @@ import { useDrag, useDrop } from 'react-dnd';
 
 import nodePath from 'path';
 
-import { pathUtils } from '@growi/core';
+import { pathUtils, pagePathUtils } from '@growi/core';
 
 import { toastWarning, toastError, toastSuccess } from '~/client/util/apiNotification';
 
 import { useSWRxPageChildren } from '~/stores/page-listing';
+import { apiv3Put, apiv3Post } from '~/client/util/apiv3-client';
 import { IPageForPageDeleteModal } from '~/stores/modal';
-import { apiv3Put } from '~/client/util/apiv3-client';
 
 import TriangleIcon from '~/components/Icons/TriangleIcon';
 import { bookmark, unbookmark } from '~/client/services/page-operation';
@@ -257,12 +257,38 @@ const Item: FC<ItemProps> = (props: ItemProps) => {
     onClickDeleteMenuItem(pageToDelete);
   }, [page, onClickDeleteMenuItem]);
 
-  const onPressEnterForCreateHandler = (inputText: string) => {
+  const onPressEnterForCreateHandler = async(inputText: string) => {
     setNewPageInputShown(false);
     const parentPath = pathUtils.addTrailingSlash(page.path as string);
     const newPagePath = `${parentPath}${inputText}`;
-    console.log(newPagePath);
-    // TODO: https://redmine.weseek.co.jp/issues/87943
+    const isCreatable = pagePathUtils.isCreatablePage(newPagePath);
+
+    if (!isCreatable) {
+      toastWarning(t('you_can_not_create_page_with_this_name'));
+      return;
+    }
+
+    // TODO 88261: Get the isEnabledAttachTitleHeader by SWR
+    // const initBody = '';
+    // const { isEnabledAttachTitleHeader } = props.appContainer.getConfig();
+    // if (isEnabledAttachTitleHeader) {
+    //   initBody = pathUtils.attachTitleHeader(newPagePath);
+    // }
+
+    try {
+      await apiv3Post('/pages/', {
+        path: newPagePath,
+        body: '',
+        grant: page.grant,
+        grantUserGroupId: page.grantedGroup,
+        createFromPageTree: true,
+      });
+      mutateChildren();
+      toastSuccess(t('successfully_saved_the_page'));
+    }
+    catch (err) {
+      toastError(err);
+    }
   };
 
   const inputValidator = (title: string | null): AlertInfo | null => {

+ 4 - 1
packages/app/src/components/Sidebar/PageTree/ItemsTree.tsx

@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
 import { IPageHasId } from '../../../interfaces/page';
 import { ItemNode } from './ItemNode';
 import Item from './Item';
-import { useSWRxPageAncestorsChildren, useSWRxRootPage } from '../../../stores/page-listing';
+import { useSWRxPageAncestorsChildren, useSWRxPageChildren, useSWRxRootPage } from '../../../stores/page-listing';
 import { TargetAndAncestors } from '~/interfaces/page-listing-results';
 import { toastError, toastSuccess } from '~/client/util/apiNotification';
 import {
@@ -109,6 +109,7 @@ const ItemsTree: FC<ItemsTreeProps> = (props: ItemsTreeProps) => {
   const { t } = useTranslation();
 
   const { data: ancestorsChildrenData, error: error1 } = useSWRxPageAncestorsChildren(targetPath);
+  const { mutate: mutateChildren } = useSWRxPageChildren(targetPathOrId);
   const { data: rootPageData, error: error2 } = useSWRxRootPage();
   const { open: openDuplicateModal } = usePageDuplicateModal();
   const { open: openRenameModal } = usePageRenameModal();
@@ -136,6 +137,8 @@ const ItemsTree: FC<ItemsTreeProps> = (props: ItemsTreeProps) => {
       return;
     }
 
+    mutateChildren();
+
     const path = pathOrPathsToDelete;
 
     if (isRecursively) {

+ 9 - 13
packages/app/src/interfaces/search.ts

@@ -1,11 +1,5 @@
 import { IPageInfoAll, IPageWithMeta } from './page';
 
-export enum CheckboxType {
-  NONE_CHECKED = 'noneChecked',
-  INDETERMINATE = 'indeterminate',
-  ALL_CHECKED = 'allChecked',
-}
-
 export type IPageSearchMeta = {
   bookmarkCount?: number,
   elasticSearchResult?: {
@@ -19,18 +13,20 @@ export const isIPageSearchMeta = (meta: IPageInfoAll | (IPageInfoAll & IPageSear
   return meta != null && 'elasticSearchResult' in meta;
 };
 
-export type IFormattedSearchResult = {
-  data: IPageWithMeta<IPageSearchMeta>[]
-
-  totalCount: number
+export type ISearchResult<T > = ISearchResultMeta & {
+  data: T[],
+}
 
+export type ISearchResultMeta = {
   meta: {
-    total: number
     took?: number
-    count?: number
-  }
+    total: number
+    hitsCount: number
+  },
 }
 
+export type IFormattedSearchResult = ISearchResult<IPageWithMeta<IPageSearchMeta>>;
+
 export const SORT_AXIS = {
   RELATION_SCORE: 'relationScore',
   CREATED_AT: 'createdAt',

+ 2 - 12
packages/app/src/server/interfaces/search.ts

@@ -1,5 +1,6 @@
 /* eslint-disable camelcase */
 import { SearchDelegatorName } from '~/interfaces/named-query';
+import { ISearchResult } from '~/interfaces/search';
 
 
 export type QueryTerms = {
@@ -25,18 +26,7 @@ export interface SearchResolver{
 
 export interface SearchDelegator<T = unknown> {
   name?: SearchDelegatorName
-  search(data: SearchableData | null, user, userGroups, option): Promise<Result<T> & MetaData>
-}
-
-export type Result<T> = {
-  data: T[]
-}
-
-export type MetaData = {
-  meta: {
-    [key:string]: any,
-    total: number,
-  }
+  search(data: SearchableData | null, user, userGroups, option): Promise<ISearchResult<T>>
 }
 
 export type SearchableData = {

+ 33 - 0
packages/app/src/server/models/obsolete-page.js

@@ -189,6 +189,39 @@ export class PageQueryBuilder {
     return this;
   }
 
+  async addConditionForParentNormalization(user) {
+    // determine UserGroup condition
+    let userGroups = null;
+    if (user != null) {
+      const UserGroupRelation = mongoose.model('UserGroupRelation');
+      userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
+    }
+
+    const grantConditions = [
+      { grant: null },
+      { grant: GRANT_PUBLIC },
+    ];
+
+    if (user != null) {
+      grantConditions.push(
+        { grant: GRANT_OWNER, grantedUsers: user._id },
+      );
+    }
+
+    if (userGroups != null && userGroups.length > 0) {
+      grantConditions.push(
+        { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
+      );
+    }
+
+    this.query = this.query
+      .and({
+        $or: grantConditions,
+      });
+
+    return this;
+  }
+
   addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
     const grantConditions = [
       { grant: null },

+ 17 - 2
packages/app/src/server/models/page.ts

@@ -167,7 +167,7 @@ schema.statics.createEmptyPage = async function(
  * @param exPage a page document to be replaced
  * @returns Promise<void>
  */
-schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?): Promise<void> {
+schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false): Promise<void> {
   // find parent
   const parent = await this.findOne({ _id: exPage.parent });
   if (parent == null) {
@@ -201,6 +201,12 @@ schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?
   };
 
   await this.bulkWrite([operationForNewTarget, operationsForChildren]);
+
+  const isExPageEmpty = exPage.isEmpty;
+  if (deleteExPageIfEmpty && isExPageEmpty) {
+    await this.deleteOne({ _id: exPage._id });
+    logger.warn('Deleted empty page since it was replaced with another page.');
+  }
 };
 
 /**
@@ -219,7 +225,7 @@ schema.statics.getParentAndFillAncestors = async function(path: string): Promise
   /*
    * Fill parents if parent is null
    */
-  const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
+  const ancestorPaths = collectAncestorPaths(path, [path]); // paths of parents need to be created
 
   // just create ancestors with empty pages
   await this.createEmptyPagesByPaths(ancestorPaths);
@@ -577,6 +583,15 @@ schema.statics.findByPageIdsToEdit = async function(ids, user, shouldIncludeEmpt
   return pages;
 };
 
+schema.statics.normalizeDescendantCountById = async function(pageId) {
+  const children = await this.find({ parent: pageId });
+
+  const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
+  const sumChildPages = children.filter(p => !p.isEmpty).length;
+
+  return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
+};
+
 export type PageCreateOptions = {
   format?: string
   grantUserGroupId?: ObjectIdLike

+ 3 - 0
packages/app/src/server/models/revision.js

@@ -10,6 +10,9 @@ module.exports = function(crowi) {
   const mongoose = require('mongoose');
   const mongoosePaginate = require('mongoose-paginate-v2');
 
+  // allow empty strings
+  mongoose.Schema.Types.String.checkRequired(v => v != null);
+
   const ObjectId = mongoose.Schema.Types.ObjectId;
   const revisionSchema = new mongoose.Schema({
     // OBSOLETE path: { type: String, required: true, index: true }

+ 8 - 4
packages/app/src/server/routes/apiv3/pages.js

@@ -159,8 +159,8 @@ module.exports = (crowi) => {
 
   const validator = {
     createPage: [
-      body('body').exists().not().isEmpty({ ignore_whitespace: true })
-        .withMessage('body is required'),
+      body('body').exists()
+        .withMessage('body is re quired but an empty string is allowed'),
       body('path').exists().not().isEmpty({ ignore_whitespace: true })
         .withMessage('path is required'),
       body('grant').if(value => value != null).isInt({ min: 0, max: 5 }).withMessage('grant must be integer from 1 to 5'),
@@ -168,6 +168,7 @@ module.exports = (crowi) => {
       body('isSlackEnabled').if(value => value != null).isBoolean().withMessage('isSlackEnabled must be boolean'),
       body('slackChannels').if(value => value != null).isString().withMessage('slackChannels must be string'),
       body('pageTags').if(value => value != null).isArray().withMessage('pageTags must be array'),
+      body('createFromPageTree').optional().isBoolean().withMessage('createFromPageTree must be boolean'),
     ],
     renamePage: [
       body('pageId').isMongoId().withMessage('pageId is required'),
@@ -244,6 +245,9 @@ module.exports = (crowi) => {
    *                    type: array
    *                    items:
    *                      $ref: '#/components/schemas/Tag'
+   *                  createFromPageTree:
+   *                    type: boolean
+   *                    description: Whether the page was created from the page tree or not
    *                required:
    *                  - body
    *                  - path
@@ -797,7 +801,7 @@ module.exports = (crowi) => {
     }
     else {
       try {
-        await crowi.pageService.normalizeParentByPageIds(pageIds);
+        await crowi.pageService.normalizeParentByPageIds(pageIds, req.user);
       }
       catch (err) {
         return res.apiv3Err(new ErrorV3(`Failed to migrate pages: ${err.message}`), 500);
@@ -810,7 +814,7 @@ module.exports = (crowi) => {
   router.get('/v5-migration-status', accessTokenParser, loginRequired, async(req, res) => {
     try {
       const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
-      const migratablePagesCount = req.user != null ? await crowi.pageService.v5MigratablePrivatePagesCount(req.user) : null;
+      const migratablePagesCount = req.user != null ? await crowi.pageService.countPagesCanNormalizeParentByUser(req.user) : null; // null check since not using loginRequiredStrictly
       return res.apiv3({ isV5Compatible, migratablePagesCount });
     }
     catch (err) {

+ 1 - 1
packages/app/src/server/routes/page.js

@@ -900,7 +900,7 @@ module.exports = function(crowi, app) {
    * - If revision_id is not specified => force update by the new contents.
    */
   api.update = async function(req, res) {
-    const pageBody = req.body.body || null;
+    const pageBody = body ?? null;
     const pageId = req.body.page_id || null;
     const revisionId = req.body.revision_id || null;
     const grant = req.body.grant || null;

+ 16 - 8
packages/app/src/server/service/page-grant.ts

@@ -233,7 +233,7 @@ class PageGrantService {
       .addConditionToSortPagesByDescPath()
       .query
       .exec();
-    const testAncestor = ancestors[0];
+    const testAncestor = ancestors[0]; // TODO: consider when duplicate testAncestors exist
     if (testAncestor == null) {
       throw Error('testAncestor must exist');
     }
@@ -320,7 +320,9 @@ class PageGrantService {
 
   /**
    * About the rule of validation, see: https://dev.growi.org/61b2cdabaa330ce7d8152844
-   * Only v5 schema pages will be used to compare.
+   * Only v5 schema pages will be used to compare by default (Set includeNotMigratedPages to true to include v4 schema pages as well).
+   * When comparing, it will use path regex to collect pages instead of using parent attribute of the Page model. This is reasonable since
+   * using the path attribute is safer than using the parent attribute in this case. 2022.02.13 -- Taichi Masuyama
    * @returns Promise<boolean>
    */
   async isGrantNormalized(
@@ -344,7 +346,13 @@ class PageGrantService {
     return this.processValidation(comparableTarget, comparableAncestor, comparableDescendants);
   }
 
-  async separateNormalizedAndNonNormalizedPages(pageIds: ObjectIdLike[]): Promise<[(PageDocument & { _id: any })[], (PageDocument & { _id: any })[]]> {
+  /**
+   * Separate normalizable pages and NOT normalizable pages by PageService.prototype.isGrantNormalized method.
+   * normalizable pages = Pages which are able to run normalizeParentRecursively method (grant & userGroup rule is correct)
+   * @param pageIds pageIds to be tested
+   * @returns a tuple with the first element of normalizable pages and the second element of NOT normalizable pages
+   */
+  async separateNormalizableAndNotNormalizablePages(pageIds: ObjectIdLike[]): Promise<[(PageDocument & { _id: any })[], (PageDocument & { _id: any })[]]> {
     if (pageIds.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
       throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
     }
@@ -354,8 +362,8 @@ class PageGrantService {
     const shouldCheckDescendants = true;
     const shouldIncludeNotMigratedPages = true;
 
-    const normalizedPages: (PageDocument & { _id: any })[] = [];
-    const nonNormalizedPages: (PageDocument & { _id: any })[] = []; // can be used to tell user which page failed to migrate
+    const normalizable: (PageDocument & { _id: any })[] = [];
+    const nonNormalizable: (PageDocument & { _id: any })[] = []; // can be used to tell user which page failed to migrate
 
     const builder = new PageQueryBuilder(Page.find());
     builder.addConditionToListByPageIdsArray(pageIds);
@@ -369,14 +377,14 @@ class PageGrantService {
 
       const isNormalized = await this.isGrantNormalized(path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants, shouldIncludeNotMigratedPages);
       if (isNormalized) {
-        normalizedPages.push(page);
+        normalizable.push(page);
       }
       else {
-        nonNormalizedPages.push(page);
+        nonNormalizable.push(page);
       }
     }
 
-    return [normalizedPages, nonNormalizedPages];
+    return [normalizable, nonNormalizable];
   }
 
 }

+ 99 - 44
packages/app/src/server/service/page.ts

@@ -9,7 +9,7 @@ import { serializePageSecurely } from '../models/serializers/page-serializer';
 import { createBatchStream } from '~/server/util/batch-stream';
 import loggerFactory from '~/utils/logger';
 import {
-  CreateMethod, generateGrantCondition, PageCreateOptions, PageModel,
+  CreateMethod, generateGrantCondition, PageCreateOptions, PageDocument, PageModel,
 } from '~/server/models/page';
 import { stringifySnapshot } from '~/models/serializers/in-app-notification-snapshot/page';
 import ActivityDefine from '../util/activityDefine';
@@ -1065,7 +1065,7 @@ class PageService {
       // replace with an empty page
       const shouldReplace = await Page.exists({ parent: page._id });
       if (shouldReplace) {
-        await Page.replaceTargetWithPage(page);
+        await Page.replaceTargetWithPage(page, null, true);
       }
 
       // update descendantCount of ancestors'
@@ -1077,10 +1077,7 @@ class PageService {
 
     let deletedPage;
     // update Revisions
-    if (page.isEmpty) {
-      await Page.remove({ _id: page._id });
-    }
-    else {
+    if (!page.isEmpty) {
       await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
       deletedPage = await Page.findByIdAndUpdate(page._id, {
         $set: {
@@ -1808,10 +1805,18 @@ class PageService {
     await inAppNotificationService.emitSocketIo(targetUsers);
   }
 
-  async normalizeParentByPageIds(pageIds: ObjectIdLike[]): Promise<void> {
+  async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
     for await (const pageId of pageIds) {
       try {
-        await this.normalizeParentByPageId(pageId);
+        const normalizedPage = await this.normalizeParentByPageId(pageId, user);
+
+        if (normalizedPage == null) {
+          logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
+        }
+        else {
+          // update descendantCount of ancestors'
+          await this.updateDescendantCountOfAncestors(pageId, normalizedPage.descendantCount, false);
+        }
       }
       catch (err) {
         // socket.emit('normalizeParentByPageIds', { error: err.message }); TODO: use socket to tell user
@@ -1819,17 +1824,23 @@ class PageService {
     }
   }
 
-  private async normalizeParentByPageId(pageId: ObjectIdLike) {
+  private async normalizeParentByPageId(pageId: ObjectIdLike, user) {
     const Page = mongoose.model('Page') as unknown as PageModel;
-    const target = await Page.findById(pageId);
+    const target = await Page.findByIdAndViewerToEdit(pageId, user);
     if (target == null) {
-      throw Error('target does not exist');
+      throw Error('target does not exist or forbidden');
     }
 
     const {
       path, grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
     } = target;
 
+    // check if any page exists at target path already
+    const existingPage = await Page.findOne({ path });
+    if (existingPage != null && !existingPage.isEmpty) {
+      throw Error('Page already exists. Please rename the page to continue.');
+    }
+
     /*
      * UserGroup & Owner validation
      */
@@ -1852,62 +1863,73 @@ class PageService {
       throw Error('Restricted pages can not be migrated');
     }
 
-    // getParentAndFillAncestors
-    const parent = await Page.getParentAndFillAncestors(target.path);
+    let updatedPage;
+
+    // replace if empty page exists
+    if (existingPage != null && existingPage.isEmpty) {
+      await Page.replaceTargetWithPage(existingPage, target, true);
+      updatedPage = await Page.findById(pageId);
+    }
+    else {
+      // getParentAndFillAncestors
+      const parent = await Page.getParentAndFillAncestors(target.path);
+      updatedPage = await Page.findOneAndUpdate({ _id: pageId }, { parent: parent._id }, { new: true });
+    }
 
-    return Page.updateOne({ _id: pageId }, { parent: parent._id });
+    return updatedPage;
   }
 
+  // TODO: this should be resumable
   async normalizeParentRecursivelyByPageIds(pageIds, user) {
+    const Page = mongoose.model('Page') as unknown as PageModel;
+
     if (pageIds == null || pageIds.length === 0) {
       logger.error('pageIds is null or 0 length.');
       return;
     }
 
-    let normalizedIds;
-    let notNormalizedPaths;
+    if (pageIds.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
+      throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
+    }
+
+    let normalizablePages;
+    let nonNormalizablePages;
     try {
-      [normalizedIds, notNormalizedPaths] = await this.crowi.pageGrantService.separateNormalizedAndNonNormalizedPages(pageIds);
+      [normalizablePages, nonNormalizablePages] = await this.crowi.pageGrantService.separateNormalizableAndNotNormalizablePages(pageIds);
     }
     catch (err) {
       throw err;
     }
 
-    if (normalizedIds.length === 0) {
+    if (normalizablePages.length === 0) {
       // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
       return;
     }
 
-    if (notNormalizedPaths.length !== 0) {
-      // TODO: iterate notNormalizedPaths and send socket error to client so that the user can know which path failed to migrate
+    if (nonNormalizablePages.length !== 0) {
+      // TODO: iterate nonNormalizablePages and send socket error to client so that the user can know which path failed to migrate
       // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
     }
 
-    /*
-     * generate regexps
-     */
-    const Page = mongoose.model('Page') as unknown as PageModel;
-
-    let pages;
-    try {
-      pages = await Page.findByPageIdsToEdit(pageIds, user, false);
-    }
-    catch (err) {
-      logger.error('Failed to find pages by ids', err);
-      throw err;
-    }
-
-    // prepare no duplicated area paths
-    let paths = pages.map(p => p.path);
-    paths = omitDuplicateAreaPathFromPaths(paths);
-
-    const regexps = paths.map(path => new RegExp(`^${escapeStringRegexp(path)}`));
+    const pagesToNormalize = omitDuplicateAreaPageFromPages(normalizablePages);
+    const pageIdsToNormalize = pagesToNormalize.map(p => p._id);
+    const pathsToNormalize = Array.from(new Set(pagesToNormalize.map(p => p.path)));
 
     // TODO: insertMany PageOperationBlock
 
-    // migrate recursively
+    // for updating descendantCount
+    const pageIdToExDescendantCountMap = new Map<ObjectIdLike, number>();
+
+    // MAIN PROCESS migrate recursively
+    const regexps = pathsToNormalize.map(p => new RegExp(`^${escapeStringRegexp(p)}`, 'i'));
     try {
       await this.normalizeParentRecursively(null, regexps);
+
+      // find pages to save descendantCount of normalized pages (only pages in pageIds parameter of this method)
+      const pagesBeforeUpdatingDescendantCount = await Page.findByIdsAndViewer(pageIdsToNormalize, user);
+      pagesBeforeUpdatingDescendantCount.forEach((p) => {
+        pageIdToExDescendantCountMap.set(p._id.toString(), p.descendantCount);
+      });
     }
     catch (err) {
       logger.error('V5 initial miration failed.', err);
@@ -1915,6 +1937,28 @@ class PageService {
 
       throw err;
     }
+
+    // POST MAIN PROCESS update descendantCount
+    try {
+      // update descendantCount of self and descendant pages first
+      for await (const path of pathsToNormalize) {
+        await this.updateDescendantCountOfSelfAndDescendants(path);
+      }
+
+      // find pages again to get updated descendantCount
+      // then calculate inc
+      const pagesAfterUpdatingDescendantCount = await Page.findByIdsAndViewer(pageIdsToNormalize, user);
+      for await (const page of pagesAfterUpdatingDescendantCount) {
+        const exDescendantCount = pageIdToExDescendantCountMap.get(page._id.toString()) || 0;
+        const newDescendantCount = page.descendantCount;
+        const inc = newDescendantCount - exDescendantCount;
+        await this.updateDescendantCountOfAncestors(page._id, inc, false);
+      }
+    }
+    catch (err) {
+      logger.error('Failed to update descendantCount after normalizing parent:', err);
+      throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
+    }
   }
 
   async _isPagePathIndexUnique() {
@@ -2194,12 +2238,23 @@ class PageService {
     }
   }
 
-  async v5MigratablePrivatePagesCount(user) {
+  async countPagesCanNormalizeParentByUser(user): Promise<number> {
     if (user == null) {
       throw Error('user is required');
     }
-    const Page = this.crowi.model('Page');
-    return Page.count({ parent: null, creator: user, grant: { $ne: Page.GRANT_PUBLIC } });
+
+    const Page = mongoose.model('Page') as unknown as PageModel;
+    const { PageQueryBuilder } = Page;
+
+    const builder = new PageQueryBuilder(Page.count(), false);
+    builder.addConditionAsNotMigrated();
+    builder.addConditionAsNonRootPage();
+    builder.addConditionToExcludeTrashed();
+    await builder.addConditionForParentNormalization(user);
+
+    const nMigratablePages = await builder.query.exec();
+
+    return nMigratablePages;
   }
 
   /**
@@ -2207,7 +2262,7 @@ class PageService {
    * - page that has the same path as the provided path
    * - pages that are descendants of the above page
    */
-  async updateDescendantCountOfSelfAndDescendants(path) {
+  async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
     const BATCH_SIZE = 200;
     const Page = this.crowi.model('Page');
 

+ 8 - 6
packages/app/src/server/service/search-delegator/elasticsearch.ts

@@ -9,12 +9,14 @@ import streamToPromise from 'stream-to-promise';
 
 import { createBatchStream } from '../../util/batch-stream';
 import loggerFactory from '~/utils/logger';
-import { PageDocument, PageModel } from '../../models/page';
+import { PageModel } from '../../models/page';
 import {
-  MetaData, SearchDelegator, Result, SearchableData, QueryTerms,
+  SearchDelegator, SearchableData, QueryTerms,
 } from '../../interfaces/search';
 import { SearchDelegatorName } from '~/interfaces/named-query';
-import { SORT_AXIS, SORT_ORDER } from '~/interfaces/search';
+import {
+  IFormattedSearchResult, ISearchResult, SORT_AXIS, SORT_ORDER,
+} from '~/interfaces/search';
 import ElasticsearchClient from './elasticsearch-client';
 
 const logger = loggerFactory('growi:service:search-delegator:elasticsearch');
@@ -611,7 +613,7 @@ class ElasticsearchDelegator implements SearchDelegator<Data> {
    *   data: [ pages ...],
    * }
    */
-  async searchKeyword(query) {
+  async searchKeyword(query): Promise<IFormattedSearchResult> {
     // for debug
     if (process.env.NODE_ENV === 'development') {
       const { body: result } = await this.client.indices.validateQuery({
@@ -634,7 +636,7 @@ class ElasticsearchDelegator implements SearchDelegator<Data> {
       meta: {
         took: result.took,
         total: totalValue,
-        results: result.hits.hits.length,
+        hitsCount: result.hits.hits.length,
       },
       data: result.hits.hits.map((elm) => {
         return {
@@ -940,7 +942,7 @@ class ElasticsearchDelegator implements SearchDelegator<Data> {
     };
   }
 
-  async search(data: SearchableData, user, userGroups, option): Promise<Result<Data> & MetaData> {
+  async search(data: SearchableData, user, userGroups, option): Promise<ISearchResult<unknown>> {
     const { queryString, terms } = data;
 
     const from = option.offset || null;

+ 4 - 2
packages/app/src/server/service/search-delegator/private-legacy-pages.ts

@@ -4,9 +4,10 @@ import { PageModel, PageDocument } from '~/server/models/page';
 import { SearchDelegatorName } from '~/interfaces/named-query';
 import { IPage } from '~/interfaces/page';
 import {
-  MetaData, Result, SearchableData, SearchDelegator,
+  SearchableData, SearchDelegator,
 } from '../../interfaces/search';
 import { serializeUserSecurely } from '../../models/serializers/user-serializer';
+import { ISearchResult } from '~/interfaces/search';
 
 
 class PrivateLegacyPagesDelegator implements SearchDelegator<IPage> {
@@ -17,7 +18,7 @@ class PrivateLegacyPagesDelegator implements SearchDelegator<IPage> {
     this.name = SearchDelegatorName.PRIVATE_LEGACY_PAGES;
   }
 
-  async search(_data: SearchableData | null, user, userGroups, option): Promise<Result<IPage> & MetaData> {
+  async search(_data: SearchableData | null, user, userGroups, option): Promise<ISearchResult<IPage>> {
     const { offset, limit } = option;
 
     if (offset == null || limit == null) {
@@ -51,6 +52,7 @@ class PrivateLegacyPagesDelegator implements SearchDelegator<IPage> {
       data: pages,
       meta: {
         total: pages.length,
+        hitsCount: pages.length,
       },
     };
   }

+ 4 - 6
packages/app/src/server/service/search.ts

@@ -1,12 +1,12 @@
 import xss from 'xss';
 
 import { SearchDelegatorName } from '~/interfaces/named-query';
-import { IFormattedSearchResult } from '~/interfaces/search';
+import { IFormattedSearchResult, ISearchResult, ISearchResultMeta } from '~/interfaces/search';
 import loggerFactory from '~/utils/logger';
 
 import NamedQuery from '../models/named-query';
 import {
-  SearchDelegator, SearchQueryParser, SearchResolver, ParsedQuery, Result, MetaData, SearchableData, QueryTerms,
+  SearchDelegator, SearchQueryParser, SearchResolver, ParsedQuery, SearchableData, QueryTerms,
 } from '../interfaces/search';
 import ElasticsearchDelegator from './search-delegator/elasticsearch';
 import PrivateLegacyPagesDelegator from './search-delegator/private-legacy-pages';
@@ -236,7 +236,7 @@ class SearchService implements SearchQueryParser, SearchResolver {
     return [this.nqDelegators[SearchDelegatorName.DEFAULT], data];
   }
 
-  async searchKeyword(keyword: string, user, userGroups, searchOpts): Promise<[Result<any> & MetaData, string]> {
+  async searchKeyword(keyword: string, user, userGroups, searchOpts): Promise<[ISearchResult<unknown>, string]> {
     let parsedQuery;
     // parse
     try {
@@ -348,7 +348,7 @@ class SearchService implements SearchQueryParser, SearchResolver {
   /**
    * formatting result
    */
-  async formatSearchResult(searchResult: Result<any> & MetaData, delegatorName): Promise<IFormattedSearchResult> {
+  async formatSearchResult(searchResult: ISearchResult<any>, delegatorName): Promise<IFormattedSearchResult> {
     if (!this.checkIsFormattable(searchResult, delegatorName)) {
       const data = searchResult.data.map((page) => {
         return {
@@ -359,7 +359,6 @@ class SearchService implements SearchQueryParser, SearchResolver {
 
       return {
         data,
-        totalCount: data.length,
         meta: searchResult.meta,
       };
     }
@@ -377,7 +376,6 @@ class SearchService implements SearchQueryParser, SearchResolver {
 
     // set meta data
     result.meta = searchResult.meta;
-    result.totalCount = findPageResult.totalCount;
 
     // set search result page data
     result.data = searchResult.data.map((data) => {

+ 15 - 8
packages/app/src/server/service/user-group.ts

@@ -58,30 +58,36 @@ class UserGroupService {
       throw Error('Parent group does not exist.');
     }
 
+    /*
+     * check if able to update parent or not
+     */
 
-    // throw if parent was in its descendants
+    // throw if parent was in self and its descendants
     const descendantsWithTarget = await UserGroup.findGroupsWithDescendantsRecursively([userGroup]);
-    const descendants = descendantsWithTarget.filter(d => d._id.equals(userGroup._id));
-    if (isIncludesObjectId(descendants, parent._id)) {
+    if (isIncludesObjectId(descendantsWithTarget, parent._id)) {
       throw Error('It is not allowed to choose parent from descendant groups.');
     }
 
     // find users for comparison
     const [targetGroupUsers, parentGroupUsers] = await Promise.all(
-      [UserGroupRelation.findUserIdsByGroupId(userGroup._id), UserGroupRelation.findUserIdsByGroupId(parent?._id)], // TODO 85062: consider when parent is null to update the group as the root
+      [UserGroupRelation.findUserIdsByGroupId(userGroup._id), UserGroupRelation.findUserIdsByGroupId(parent._id)],
     );
-
     const usersBelongsToTargetButNotParent = targetGroupUsers.filter(user => !parentGroupUsers.includes(user));
+
+    // save if no users exist in both target and parent groups
+    if (targetGroupUsers.length === 0 && parentGroupUsers.length === 0) {
+      userGroup.parent = parent._id;
+      return userGroup.save();
+    }
+
     // add the target group's users to all ancestors
     if (forceUpdateParents) {
       const ancestorGroups = await UserGroup.findGroupsWithAncestorsRecursively(parent);
       const ancestorGroupIds = ancestorGroups.map(group => group._id);
 
       await UserGroupRelation.createByGroupIdsAndUserIds(ancestorGroupIds, usersBelongsToTargetButNotParent);
-
-      userGroup.parent = parent?._id; // TODO 85062: consider when parent is null to update the group as the root
     }
-    // validate related users
+    // throw if any of users in the target group is NOT included in the parent group
     else {
       const isUpdatable = usersBelongsToTargetButNotParent.length === 0;
       if (!isUpdatable) {
@@ -89,6 +95,7 @@ class UserGroupService {
       }
     }
 
+    userGroup.parent = parent._id;
     return userGroup.save();
   }
 

+ 4 - 0
packages/app/src/server/util/swigFunctions.js

@@ -171,6 +171,10 @@ module.exports = function(crowi, req, locals) {
     });
   };
 
+  locals.attachTitleHeader = function(path) {
+    return pathUtils.attachTitleHeader(path);
+  };
+
   locals.css = {
     grant(pageData) {
       if (!pageData) {

+ 2 - 2
packages/app/src/server/views/widget/not_found_content.html

@@ -17,9 +17,9 @@
 
     {% if getConfig('crowi', 'customize:isEnabledAttachTitleHeader') %}
     {% if template %}
-    <script type="text/template" id="raw-text-original"># {{ path | path2name | preventXss }}&NewLine;{{ template }}</script>
+    <script type="text/template" id="raw-text-original">{{ attachTitleHeader(path | path2name | preventXss) }}&NewLine;{{ template }}</script>
     {% else %}
-    <script type="text/template" id="raw-text-original"># {{ path | path2name | preventXss }}</script>
+    <script type="text/template" id="raw-text-original">{{ attachTitleHeader(path | path2name | preventXss) }}</script>
     {% endif %}
     {% else %}
     {% if template %}

+ 92 - 0
packages/app/src/stores/search.tsx

@@ -0,0 +1,92 @@
+import { SWRResponse } from 'swr';
+import useSWRImmutable from 'swr/immutable';
+
+import { apiGet } from '~/client/util/apiv1-client';
+
+import { IFormattedSearchResult, SORT_AXIS, SORT_ORDER } from '~/interfaces/search';
+
+
+export type ISearchConfigurations = {
+  limit: number,
+  offset?: number,
+  sort?: SORT_AXIS,
+  order?: SORT_ORDER,
+  includeTrashPages?: boolean,
+  includeUserPages?: boolean,
+}
+
+type ISearchConfigurationsFixed = {
+  limit: number,
+  offset: number,
+  sort: SORT_AXIS,
+  order: SORT_ORDER,
+  includeTrashPages: boolean,
+  includeUserPages: boolean,
+}
+
+export type ISearchConditions = ISearchConfigurationsFixed & {
+  keyword: string,
+  rawQuery: string,
+}
+
+const createSearchQuery = (keyword: string, includeTrashPages: boolean, includeUserPages: boolean): string => {
+  let query = keyword;
+
+  // pages included in specific path are not retrived when prefix is added
+  if (!includeTrashPages) {
+    query = `${query} -prefix:/trash`;
+  }
+  if (!includeUserPages) {
+    query = `${query} -prefix:/user`;
+  }
+
+  return query;
+};
+
+export const useSWRxFullTextSearch = (
+    keyword: string, configurations: ISearchConfigurations,
+): SWRResponse<IFormattedSearchResult, Error> & { conditions: ISearchConditions } => {
+
+  const {
+    limit, offset, sort, order, includeTrashPages, includeUserPages,
+  } = configurations;
+
+  const fixedConfigurations: ISearchConfigurationsFixed = {
+    limit,
+    offset: offset ?? 0,
+    sort: sort ?? SORT_AXIS.RELATION_SCORE,
+    order: order ?? SORT_ORDER.DESC,
+    includeTrashPages: includeTrashPages ?? false,
+    includeUserPages: includeUserPages ?? false,
+  };
+  const rawQuery = createSearchQuery(keyword, fixedConfigurations.includeTrashPages, fixedConfigurations.includeUserPages);
+
+  const swrResult = useSWRImmutable(
+    ['/search', keyword, fixedConfigurations],
+    (endpoint, keyword, fixedConfigurations) => {
+      const {
+        limit, offset, sort, order,
+      } = fixedConfigurations;
+
+      return apiGet(
+        endpoint, {
+          q: encodeURIComponent(rawQuery),
+          limit,
+          offset,
+          sort,
+          order,
+        },
+      // eslint-disable-next-line @typescript-eslint/no-explicit-any
+      ).then(result => result as IFormattedSearchResult);
+    },
+  );
+
+  return {
+    ...swrResult,
+    conditions: {
+      keyword,
+      rawQuery,
+      ...fixedConfigurations,
+    },
+  };
+};

+ 10 - 24
packages/app/src/styles/_search.scss

@@ -162,7 +162,8 @@
       }
     }
 
-    .search-result-meta {
+    .search-result-keyword {
+      font-size: 17.5px;
       font-weight: bold;
     }
     .search-result-select-group {
@@ -170,14 +171,14 @@
         max-width: 8rem;
       }
     }
-    .search-result-list-delete-checkbox {
-      margin: 0 10px 0 0;
-      vertical-align: middle;
-    }
-    // not show top label in search result list
-    .page-list-meta {
-      .top-label {
-        display: none;
+
+    // list group
+    .page-list {
+      // not show top label in search result list
+      .page-list-meta {
+        .top-label {
+          display: none;
+        }
       }
     }
   }
@@ -218,21 +219,6 @@
   }
 }
 
-// 2021/9/22 TODO: Remove after moving to SearchResult
-.search-page-input {
-  position: sticky;
-  top: 15px;
-  // placed at front-most
-  z-index: 15;
-
-  margin-bottom: 15px;
-
-  .input-group-btn .btn {
-    height: 34px;
-    padding: 0px 10px;
-  }
-}
-
 // support for your search
 .grw-search-table {
   caption {

+ 4 - 0
packages/app/src/styles/atoms/_custom_control.scss

@@ -1,3 +1,7 @@
+.custom-checkbox .custom-control-label::before {
+  border-radius: $border-radius !important;
+}
+
 label.custom-control-label {
   font-weight: normal;
 }

+ 0 - 0
packages/app/test/cypress/integration/2-advanced-examples/misc.spec.ts → packages/app/test/cypress/integration/0-advanced-examples/misc.spec.ts


+ 0 - 0
packages/app/test/cypress/integration/2-advanced-examples/viewport.spec.ts → packages/app/test/cypress/integration/0-advanced-examples/viewport.spec.ts


+ 6 - 1
packages/app/test/cypress/integration/2-basic-features/access-to-page.spec.ts

@@ -1,6 +1,6 @@
-const ssPrefix = 'access-to-page-';
 
 context('Access to page', () => {
+  const ssPrefix = 'access-to-page-';
 
   let connectSid: string | undefined;
 
@@ -30,4 +30,9 @@ context('Access to page', () => {
     cy.screenshot(`${ssPrefix}-sandbox-headers`, { capture: 'viewport' });
   });
 
+  it('/Sandbox/Math is successfully loaded', () => {
+    cy.visit('/Sandbox/Math');
+    cy.screenshot(`${ssPrefix}-sandbox-math`, { capture: 'viewport' });
+  });
+
 });

+ 48 - 0
packages/app/test/cypress/integration/3-search/access-to-result-page-directly.spec.ts

@@ -0,0 +1,48 @@
+context('Access to search result page directly', () => {
+  const ssPrefix = 'access-to-result-page-directly-';
+
+  let connectSid: string | undefined;
+
+  before(() => {
+    // login
+    cy.fixture("user-admin.json").then(user => {
+      cy.login(user.username, user.password);
+    });
+    cy.getCookie('connect.sid').then(cookie => {
+      connectSid = cookie?.value;
+    });
+  });
+
+  beforeEach(() => {
+    if (connectSid != null) {
+      cy.setCookie('connect.sid', connectSid);
+    }
+  });
+
+  it('/_search with "q" param is successfully loaded', () => {
+    cy.visit('/_search', { qs: { q: 'sandbox headers blockquotes' } });
+    // eslint-disable-next-line cypress/no-unnecessary-waiting
+    cy.wait(1000);
+    cy.screenshot(`${ssPrefix}-with-q`, { capture: 'viewport' });
+  });
+
+  it('checkboxes behaviors', () => {
+    cy.visit('/_search', { qs: { q: 'sandbox headers blockquotes' } });
+
+    cy.getByTestid('cb-select').first().click({force: true});
+    cy.screenshot(`${ssPrefix}-the-first-checkbox-on`, { capture: 'viewport' });
+    cy.getByTestid('cb-select').first().click({force: true});
+    cy.screenshot(`${ssPrefix}-the-first-checkbox-off`, { capture: 'viewport' });
+
+    // click select all checkbox
+    cy.getByTestid('cb-select-all').click({force: true});
+    cy.screenshot(`${ssPrefix}-the-select-all-checkbox-1`, { capture: 'viewport' });
+    cy.getByTestid('cb-select').first().click({force: true});
+    cy.screenshot(`${ssPrefix}-the-select-all-checkbox-2`, { capture: 'viewport' });
+    cy.getByTestid('cb-select').first().click({force: true});
+    cy.screenshot(`${ssPrefix}-the-select-all-checkbox-3`, { capture: 'viewport' });
+    cy.getByTestid('cb-select-all').click({force: true});
+    cy.screenshot(`${ssPrefix}-the-select-all-checkbox-4`, { capture: 'viewport' });
+  });
+
+});

+ 5 - 3
packages/core/src/utils/page-path-utils.ts

@@ -169,8 +169,9 @@ export const collectAncestorPaths = (path: string, ancestorPaths: string[] = [])
  * @returns omitted paths
  */
 export const omitDuplicateAreaPathFromPaths = (paths: string[]): string[] => {
-  return paths.filter((path) => {
-    const isDuplicate = paths.filter(p => (new RegExp(`^${p}\\/.+`, 'i')).test(path)).length > 0;
+  const uniquePaths = Array.from(new Set(paths));
+  return uniquePaths.filter((path) => {
+    const isDuplicate = uniquePaths.filter(p => (new RegExp(`^${p}\\/.+`, 'i')).test(path)).length > 0;
 
     return !isDuplicate;
   });
@@ -178,12 +179,13 @@ export const omitDuplicateAreaPathFromPaths = (paths: string[]): string[] => {
 
 /**
  * return pages with path without duplicate area of regexp /^${path}\/.+/i
+ * if the pages' path are the same, it will NOT omit any of them since the other attributes will not be the same
  * @param paths paths to be tested
  * @returns omitted paths
  */
 export const omitDuplicateAreaPageFromPages = (pages: any[]): any[] => {
   return pages.filter((page) => {
-    const isDuplicate = pages.filter(p => (new RegExp(`^${p.path}\\/.+`, 'i')).test(page.path)).length > 0;
+    const isDuplicate = pages.some(p => (new RegExp(`^${p.path}\\/.+`, 'i')).test(page.path));
 
     return !isDuplicate;
   });

+ 11 - 0
packages/core/src/utils/path-utils.js

@@ -106,3 +106,14 @@ export function normalizePath(path) {
   }
   return `/${match[3]}`;
 }
+
+
+/**
+ *
+ * @param {string} path
+ * @returns {string}
+ * @memberof pathUtils
+ */
+export function attachTitleHeader(path) {
+  return `# ${path}`;
+}