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

Merge branch 'feat/search-implement' into feat/77543-80335-detach-page-control-from-page-container

NEEDLEMAN3\tatsu 4 лет назад
Родитель
Сommit
c4eddc8f2e
26 измененных файлов с 674 добавлено и 452 удалено
  1. 1 0
      packages/app/config/logger/config.dev.js
  2. 4 1
      packages/app/resource/locales/en_US/translation.json
  3. 4 1
      packages/app/resource/locales/ja_JP/translation.json
  4. 4 1
      packages/app/resource/locales/zh_CN/translation.json
  5. 3 0
      packages/app/resource/search/mappings.json
  6. 6 6
      packages/app/src/components/PaginationWrapper.jsx
  7. 2 1
      packages/app/src/components/SearchForm.jsx
  8. 164 25
      packages/app/src/components/SearchPage.jsx
  9. 39 0
      packages/app/src/components/SearchPage/DeleteAllButton.jsx
  10. 42 0
      packages/app/src/components/SearchPage/IncludeSpecificPathButton.jsx
  11. 69 0
      packages/app/src/components/SearchPage/SearchControl.tsx
  12. 28 9
      packages/app/src/components/SearchPage/SearchPageForm.jsx
  13. 43 0
      packages/app/src/components/SearchPage/SearchPageLayout.tsx
  14. 0 350
      packages/app/src/components/SearchPage/SearchResult.jsx
  15. 50 0
      packages/app/src/components/SearchPage/SearchResultContent.tsx
  16. 35 48
      packages/app/src/components/SearchPage/SearchResultList.jsx
  17. 99 0
      packages/app/src/components/SearchPage/SearchResultListItem.tsx
  18. 3 1
      packages/app/src/server/events/page.js
  19. 2 0
      packages/app/src/server/models/page.js
  20. 8 4
      packages/app/src/server/routes/search.js
  21. 1 0
      packages/app/src/server/service/page.js
  22. 24 4
      packages/app/src/server/service/search-delegator/elasticsearch.js
  23. 29 0
      packages/app/src/server/service/search.js
  24. 3 1
      packages/app/src/styles/_search.scss
  25. 3 0
      packages/app/src/styles/theme/_apply-colors.scss
  26. 8 0
      packages/ui/src/components/PagePath/PagePathLabel.jsx

+ 1 - 0
packages/app/config/logger/config.dev.js

@@ -35,5 +35,6 @@ module.exports = {
   'growi:services:*': 'debug',
   'growi:services:*': 'debug',
   // 'growi:StaffCredit': 'debug',
   // 'growi:StaffCredit': 'debug',
   // 'growi:cli:StickyStretchableScroller': 'debug',
   // 'growi:cli:StickyStretchableScroller': 'debug',
+  'growi:searchResultList': 'debug',
 
 
 };
 };

+ 4 - 1
packages/app/resource/locales/en_US/translation.json

@@ -64,6 +64,7 @@
   "Include Attachment File": "Include Attachment File",
   "Include Attachment File": "Include Attachment File",
   "Include Comment": "Include Comment",
   "Include Comment": "Include Comment",
   "Include Subordinated Page": "Include Subordinated Page",
   "Include Subordinated Page": "Include Subordinated Page",
+  "Include Subordinated Target Page": "include {{target}}",
   "All Subordinated Page": "All Subordinated Page",
   "All Subordinated Page": "All Subordinated Page",
   "Specify Hierarchy": "Specify Hierarchy",
   "Specify Hierarchy": "Specify Hierarchy",
   "Submitted the request to create the archive": "Submitted the request to create the archive",
   "Submitted the request to create the archive": "Submitted the request to create the archive",
@@ -572,7 +573,9 @@
     "delete": "Delete",
     "delete": "Delete",
     "check_all": "Check all",
     "check_all": "Check all",
     "deletion_modal_header": "Delete page",
     "deletion_modal_header": "Delete page",
-    "delete_completely": "Delete completely"
+    "delete_completely": "Delete completely",
+    "include_certain_path" : "Include {{pathToInclude}} path ",
+    "delete_all_selected_page" : "Delete All"
   },
   },
   "security_setting": {
   "security_setting": {
     "Guest Users Access": "Guest users access",
     "Guest Users Access": "Guest users access",

+ 4 - 1
packages/app/resource/locales/ja_JP/translation.json

@@ -64,6 +64,7 @@
   "Include Attachment File": "添付ファイルも含める",
   "Include Attachment File": "添付ファイルも含める",
   "Include Comment": "コメントも含める",
   "Include Comment": "コメントも含める",
   "Include Subordinated Page": "配下ページも含める",
   "Include Subordinated Page": "配下ページも含める",
+  "Include Subordinated Target Page": "{{target}} 下を含む",
   "All Subordinated Page": "全ての配下ページ",
   "All Subordinated Page": "全ての配下ページ",
   "Specify Hierarchy": "階層の深さを指定",
   "Specify Hierarchy": "階層の深さを指定",
   "Submitted the request to create the archive": "アーカイブ作成のリクエストを正常に送信しました",
   "Submitted the request to create the archive": "アーカイブ作成のリクエストを正常に送信しました",
@@ -572,7 +573,9 @@
     "delete": "削除",
     "delete": "削除",
     "check_all": "すべてチェック",
     "check_all": "すべてチェック",
     "deletion_modal_header": "以下のページを削除",
     "deletion_modal_header": "以下のページを削除",
-    "delete_completely": "完全に削除する"
+    "delete_completely": "完全に削除する",
+    "include_certain_path": "{{pathToInclude}}下を含む ",
+    "delete_all_selected_page" : "一括削除"
   },
   },
   "security_setting": {
   "security_setting": {
     "Guest Users Access": "ゲストユーザーのアクセス",
     "Guest Users Access": "ゲストユーザーのアクセス",

+ 4 - 1
packages/app/resource/locales/zh_CN/translation.json

@@ -65,6 +65,7 @@
   "Include Attachment File": "包含附件",
   "Include Attachment File": "包含附件",
   "Include Comment": "包含评论",
   "Include Comment": "包含评论",
   "Include Subordinated Page": "包括子页面",
   "Include Subordinated Page": "包括子页面",
+  "Include Subordinated Target Page": "包括 {{target}}",
   "All Subordinated Page": "所有子页面",
   "All Subordinated Page": "所有子页面",
   "Specify Hierarchy": "指定层级",
   "Specify Hierarchy": "指定层级",
   "Submitted the request to create the archive": "提交创建归档请求",
   "Submitted the request to create the archive": "提交创建归档请求",
@@ -844,7 +845,9 @@
 		"delete": "删除",
 		"delete": "删除",
 		"check_all": "全部检查",
 		"check_all": "全部检查",
 		"deletion_modal_header": "删除页",
 		"deletion_modal_header": "删除页",
-		"delete_completely": "完全删除"
+		"delete_completely": "完全删除",
+    "include_certain_path": "包含 {{pathToInclude}} 路径 ",
+    "delete_all_selected_page": "删除所有"
 	},
 	},
 	"to_cloud_settings": "進入 GROWI.cloud 的管理界面",
 	"to_cloud_settings": "進入 GROWI.cloud 的管理界面",
 	"login": {
 	"login": {

+ 3 - 0
packages/app/resource/search/mappings.json

@@ -74,6 +74,9 @@
         "bookmark_count": {
         "bookmark_count": {
           "type": "integer"
           "type": "integer"
         },
         },
+        "seenUsers_count":{
+          "type": "integer"
+        },
         "like_count": {
         "like_count": {
           "type": "integer"
           "type": "integer"
         },
         },

+ 6 - 6
packages/app/src/components/PaginationWrapper.jsx

@@ -63,10 +63,10 @@ const PaginationWrapper = React.memo((props) => {
     if (activePage !== 1) {
     if (activePage !== 1) {
       paginationItems.push(
       paginationItems.push(
         <PaginationItem key="painationItemFirst">
         <PaginationItem key="painationItemFirst">
-          <PaginationLink first onClick={() => { return changePage(1) }} />
+          <PaginationLink first onClick={() => { return changePage != null && changePage(1) }} />
         </PaginationItem>,
         </PaginationItem>,
         <PaginationItem key="painationItemPrevious">
         <PaginationItem key="painationItemPrevious">
-          <PaginationLink previous onClick={() => { return changePage(activePage - 1) }} />
+          <PaginationLink previous onClick={() => { return changePage != null && changePage(activePage - 1) }} />
         </PaginationItem>,
         </PaginationItem>,
       );
       );
     }
     }
@@ -93,7 +93,7 @@ const PaginationWrapper = React.memo((props) => {
     for (let number = paginationStart; number <= maxViewPageNum; number++) {
     for (let number = paginationStart; number <= maxViewPageNum; number++) {
       paginationItems.push(
       paginationItems.push(
         <PaginationItem key={`paginationItem-${number}`} active={number === activePage}>
         <PaginationItem key={`paginationItem-${number}`} active={number === activePage}>
-          <PaginationLink onClick={() => { return changePage(number) }}>
+          <PaginationLink onClick={() => { return changePage != null && changePage(number) }}>
             {number}
             {number}
           </PaginationLink>
           </PaginationLink>
         </PaginationItem>,
         </PaginationItem>,
@@ -112,10 +112,10 @@ const PaginationWrapper = React.memo((props) => {
     if (totalPage !== activePage) {
     if (totalPage !== activePage) {
       paginationItems.push(
       paginationItems.push(
         <PaginationItem key="painationItemNext">
         <PaginationItem key="painationItemNext">
-          <PaginationLink next onClick={() => { return changePage(activePage + 1) }} />
+          <PaginationLink next onClick={() => { return changePage != null && changePage(activePage + 1) }} />
         </PaginationItem>,
         </PaginationItem>,
         <PaginationItem key="painationItemLast">
         <PaginationItem key="painationItemLast">
-          <PaginationLink last onClick={() => { return changePage(totalPage) }} />
+          <PaginationLink last onClick={() => { return changePage != null && changePage(totalPage) }} />
         </PaginationItem>,
         </PaginationItem>,
       );
       );
     }
     }
@@ -159,7 +159,7 @@ const PaginationWrapper = React.memo((props) => {
 
 
 PaginationWrapper.propTypes = {
 PaginationWrapper.propTypes = {
   activePage: PropTypes.number.isRequired,
   activePage: PropTypes.number.isRequired,
-  changePage: PropTypes.func.isRequired,
+  changePage: PropTypes.func,
   totalItemsCount: PropTypes.number.isRequired,
   totalItemsCount: PropTypes.number.isRequired,
   pagingLimit: PropTypes.number,
   pagingLimit: PropTypes.number,
   align: PropTypes.string,
   align: PropTypes.string,

+ 2 - 1
packages/app/src/components/SearchForm.jsx

@@ -1,5 +1,6 @@
 import React from 'react';
 import React from 'react';
 import PropTypes from 'prop-types';
 import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
 import { withUnstatedContainers } from './UnstatedUtils';
 import { withUnstatedContainers } from './UnstatedUtils';
 import AppContainer from '~/client/services/AppContainer';
 import AppContainer from '~/client/services/AppContainer';
 
 
@@ -174,4 +175,4 @@ SearchForm.defaultProps = {
   onInputChange: () => {},
   onInputChange: () => {},
 };
 };
 
 
-export default SearchFormWrapper;
+export default withTranslation()(SearchFormWrapper);

+ 164 - 25
packages/app/src/components/SearchPage.jsx

@@ -8,24 +8,45 @@ import { withUnstatedContainers } from './UnstatedUtils';
 import AppContainer from '~/client/services/AppContainer';
 import AppContainer from '~/client/services/AppContainer';
 
 
 import { toastError } from '~/client/util/apiNotification';
 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 SearchPageForm from './SearchPage/SearchPageForm';
-import SearchResult from './SearchPage/SearchResult';
+export const specificPathNames = {
+  user: '/user',
+  trash: '/trash',
+};
 
 
 class SearchPage extends React.Component {
 class SearchPage extends React.Component {
 
 
   constructor(props) {
   constructor(props) {
     super(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 = {
     this.state = {
       searchingKeyword: decodeURI(this.props.query.q) || '',
       searchingKeyword: decodeURI(this.props.query.q) || '',
       searchedKeyword: '',
       searchedKeyword: '',
       searchedPages: [],
       searchedPages: [],
       searchResultMeta: {},
       searchResultMeta: {},
+      selectedPage: {},
+      selectedPages: new Set(),
+      searchResultCount: 0,
+      activePage: 1,
+      pagingLimit: 3, // change to an appropriate limit number
+      excludeUsersHome: true,
+      excludeTrash: true,
     };
     };
 
 
-    this.search = this.search.bind(this);
     this.changeURL = this.changeURL.bind(this);
     this.changeURL = this.changeURL.bind(this);
+    this.search = this.search.bind(this);
+    this.searchHandler = this.searchHandler.bind(this);
+    this.selectPage = this.selectPage.bind(this);
+    this.toggleCheckBox = this.toggleCheckBox.bind(this);
+    this.onExcludeUsersHome = this.onExcludeUsersHome.bind(this);
+    this.onExcludeTrash = this.onExcludeTrash.bind(this);
+    this.onPagingNumberChanged = this.onPagingNumberChanged.bind(this);
   }
   }
 
 
   componentDidMount() {
   componentDidMount() {
@@ -47,6 +68,14 @@ class SearchPage extends React.Component {
     return query;
     return query;
   }
   }
 
 
+  onExcludeUsersHome() {
+    this.setState({ excludeUsersHome: !this.state.excludeUsersHome });
+  }
+
+  onExcludeTrash() {
+    this.setState({ excludeTrash: !this.state.excludeTrash });
+  }
+
   changeURL(keyword, refreshHash) {
   changeURL(keyword, refreshHash) {
     let hash = window.location.hash || '';
     let hash = window.location.hash || '';
     // TODO 整理する
     // TODO 整理する
@@ -58,13 +87,48 @@ class SearchPage extends React.Component {
     }
     }
   }
   }
 
 
-  search(data) {
+  createSearchQuery(keyword) {
+    let query = keyword;
+
+    // pages included in specific path are not retrived when prefix is added
+    if (this.state.excludeTrash) {
+      query = `${query} -prefix:${specificPathNames.trash}`;
+    }
+    if (this.state.excludeUsersHome) {
+      query = `${query} -prefix:${specificPathNames.user}`;
+    }
+
+    return query;
+  }
+
+  /**
+   * this method is called when user changes paging number
+   */
+  async onPagingNumberChanged(activePage) {
+    // this.setState does not change the state immediately and following calls of this.search outside of this.setState will have old activePage state.
+    // To prevent above, pass this.search as a callback function to make sure this.search will have the latest activePage state.
+    this.setState({ activePage }, () => this.search({ keyword: this.state.searchedKeyword }));
+  }
+
+  /**
+   * this method is called when user searches by pressing Enter or using searchbox
+   */
+  async searchHandler(data) {
+    // this.setState does not change the state immediately and following calls of this.search outside of this.setState will have old activePage state.
+    // To prevent above, pass this.search as a callback function to make sure this.search will have the latest activePage state.
+    this.setState({ activePage: 1 }, () => this.search(data));
+  }
+
+  async search(data) {
     const keyword = data.keyword;
     const keyword = data.keyword;
     if (keyword === '') {
     if (keyword === '') {
       this.setState({
       this.setState({
         searchingKeyword: '',
         searchingKeyword: '',
+        searchedKeyword: '',
         searchedPages: [],
         searchedPages: [],
         searchResultMeta: {},
         searchResultMeta: {},
+        searchResultCount: 0,
+        activePage: 1,
       });
       });
 
 
       return true;
       return true;
@@ -73,37 +137,112 @@ class SearchPage extends React.Component {
     this.setState({
     this.setState({
       searchingKeyword: keyword,
       searchingKeyword: keyword,
     });
     });
-
-    this.props.appContainer.apiGet('/search', { q: keyword })
-      .then((res) => {
-        this.changeURL(keyword);
-
+    const pagingLimit = this.state.pagingLimit;
+    const offset = (this.state.activePage * pagingLimit) - pagingLimit;
+    try {
+      const res = await this.props.appContainer.apiGet('/search', {
+        q: this.createSearchQuery(keyword),
+        limit: pagingLimit,
+        offset,
+      });
+      this.changeURL(keyword);
+      if (res.data.length > 0) {
         this.setState({
         this.setState({
           searchedKeyword: keyword,
           searchedKeyword: keyword,
           searchedPages: res.data,
           searchedPages: res.data,
           searchResultMeta: res.meta,
           searchResultMeta: res.meta,
+          searchResultCount: res.meta.total,
+          selectedPage: res.data[0],
+          // reset active page if keyword changes, otherwise set the current state
+          activePage: this.state.searchedKeyword === keyword ? this.state.activePage : 1,
         });
         });
-      })
-      .catch((err) => {
-        toastError(err);
-      });
+      }
+      else {
+        this.setState({
+          searchedKeyword: keyword,
+          searchedPages: [],
+          searchResultMeta: {},
+          searchResultCount: 0,
+          selectedPage: {},
+          activePage: 1,
+        });
+      }
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }
+
+  selectPage= (pageId) => {
+    const index = this.state.searchedPages.findIndex((page) => {
+      return page._id === pageId;
+    });
+    this.setState({
+      selectedPage: this.state.searchedPages[index],
+    });
+  }
+
+  toggleCheckBox = (page) => {
+    if (this.state.selectedPages.has(page)) {
+      this.state.selectedPages.delete(page);
+    }
+    else {
+      this.state.selectedPages.add(page);
+    }
+  }
+
+  renderSearchResultContent = () => {
+    return (
+      <SearchResultContent
+        appContainer={this.props.appContainer}
+        searchingKeyword={this.state.searchingKeyword}
+        selectedPage={this.state.selectedPage}
+      >
+      </SearchResultContent>
+    );
+  }
+
+  renderSearchResultList = () => {
+    return (
+      <SearchResultList
+        pages={this.state.searchedPages}
+        deletionMode={false}
+        selectedPage={this.state.selectedPage}
+        selectedPages={this.state.selectedPages}
+        searchResultCount={this.state.searchResultCount}
+        activePage={this.state.activePage}
+        pagingLimit={this.state.pagingLimit}
+        onClickInvoked={this.selectPage}
+        onChangedInvoked={this.toggleCheckBox}
+        onPagingNumberChanged={this.onPagingNumberChanged}
+      />
+    );
+  }
+
+  renderSearchControl = () => {
+    return (
+      <SearchControl
+        searchingKeyword={this.state.searchingKeyword}
+        appContainer={this.props.appContainer}
+        onSearchInvoked={this.searchHandler}
+        onExcludeUsersHome={this.onExcludeUsersHome}
+        onExcludeTrash={this.onExcludeTrash}
+      >
+      </SearchControl>
+    );
   }
   }
 
 
   render() {
   render() {
     return (
     return (
       <div>
       <div>
-        <div className="search-page-input sps sps--abv">
-          <SearchPageForm
-            t={this.props.t}
-            onSearchFormChanged={this.search}
-            keyword={this.state.searchingKeyword}
-          />
-        </div>
-        <SearchResult
-          pages={this.state.searchedPages}
-          searchingKeyword={this.state.searchingKeyword}
+        <SearchPageLayout
+          SearchControl={this.renderSearchControl}
+          SearchResultList={this.renderSearchResultList}
+          SearchResultContent={this.renderSearchResultContent}
           searchResultMeta={this.state.searchResultMeta}
           searchResultMeta={this.state.searchResultMeta}
-        />
+          searchingKeyword={this.state.searchedKeyword}
+        >
+        </SearchPageLayout>
       </div>
       </div>
     );
     );
   }
   }

+ 39 - 0
packages/app/src/components/SearchPage/DeleteAllButton.jsx

@@ -0,0 +1,39 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import { useTranslation } from 'react-i18next';
+
+const DeleteAllButton = (props) => {
+  const { selectedPage, checked } = props;
+  const { t } = useTranslation();
+  function deleteAllSelectedPage(pagesToDelete) {
+    // TODO: implement this function
+    // https://estoc.weseek.co.jp/redmine/issues/77543
+    // do something with pagesDelete to delete them.
+  }
+  return (
+    <div>
+      <label>
+        <input
+          type="checkbox"
+          name="check-delte-all"
+          onChange={() => {
+            if (checked) {
+              deleteAllSelectedPage(selectedPage);
+            }
+          }}
+        />
+        <span className="text-danger font-weight-light">
+          <i className="icon-trash ml-3"></i>
+          {t('search_result.delete_all_selected_page')}
+        </span>
+      </label>
+    </div>
+  );
+
+};
+
+DeleteAllButton.propTypes = {
+  selectedPage: PropTypes.array.isRequired,
+  checked: PropTypes.bool.isRequired,
+};
+export default DeleteAllButton;

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

@@ -0,0 +1,42 @@
+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;

+ 69 - 0
packages/app/src/components/SearchPage/SearchControl.tsx

@@ -0,0 +1,69 @@
+import React, { FC } from 'react';
+import { useTranslation } from 'react-i18next';
+import SearchPageForm from './SearchPageForm';
+import AppContainer from '../../client/services/AppContainer';
+
+type Props = {
+  searchingKeyword: string,
+  appContainer: AppContainer,
+  onSearchInvoked: (data : any[]) => boolean,
+  onExcludeUsersHome?: () => void,
+  onExcludeTrash?: () => void,
+}
+
+const SearchControl: FC <Props> = (props: Props) => {
+  // Temporaly workaround for lint error
+  // later needs to be fixed: SearchControl to typescript componet
+  const SearchPageFormTypeAny : any = SearchPageForm;
+  const { t } = useTranslation('');
+
+  const onExcludeUsersHome = () => {
+    if (props.onExcludeUsersHome != null) {
+      props.onExcludeUsersHome();
+    }
+  };
+
+  const onExcludeTrash = () => {
+    if (props.onExcludeTrash != null) {
+      props.onExcludeTrash();
+    }
+  };
+
+  return (
+    <div className="">
+      <div className="search-page-input sps sps--abv">
+        <SearchPageFormTypeAny
+          keyword={props.searchingKeyword}
+          appContainer={props.appContainer}
+          onSearchFormChanged={props.onSearchInvoked}
+        />
+      </div>
+      {/* TODO: replace the following elements deleteAll button , relevance button and include specificPath button component */}
+      <div className="d-flex my-4">
+        <div className="d-flex align-items-center border rounded border-gray px-2 py-1 mr-2 ml-auto">
+          <label className="my-0 mr-2" htmlFor="flexCheckDefault">
+            {t('Include Subordinated Target Page', { target: '/user' })}
+          </label>
+          <input
+            type="checkbox"
+            id="flexCheckDefault"
+            onClick={() => onExcludeUsersHome()}
+          />
+        </div>
+        <div className="d-flex align-items-center border rounded border-gray px-2 mr-3">
+          <label className="my-0 mr-2" htmlFor="flexCheckChecked">
+            {t('Include Subordinated Target Page', { target: '/trash' })}
+          </label>
+          <input
+            type="checkbox"
+            id="flexCheckChecked"
+            onClick={() => onExcludeTrash()}
+          />
+        </div>
+      </div>
+    </div>
+  );
+};
+
+
+export default SearchControl;

+ 28 - 9
packages/app/src/components/SearchPage/SearchPageForm.jsx

@@ -4,6 +4,9 @@ import PropTypes from 'prop-types';
 import { withUnstatedContainers } from '../UnstatedUtils';
 import { withUnstatedContainers } from '../UnstatedUtils';
 import AppContainer from '~/client/services/AppContainer';
 import AppContainer from '~/client/services/AppContainer';
 import SearchForm from '../SearchForm';
 import SearchForm from '../SearchForm';
+import loggerFactory from '~/utils/logger';
+
+const logger = loggerFactory('growi:searchPageForm');
 
 
 // Search.SearchForm
 // Search.SearchForm
 class SearchPageForm extends React.Component {
 class SearchPageForm extends React.Component {
@@ -21,9 +24,14 @@ class SearchPageForm extends React.Component {
   }
   }
 
 
   search() {
   search() {
-    const keyword = this.state.keyword;
-    this.props.onSearchFormChanged({ keyword });
-    this.setState({ searchedKeyword: keyword });
+    if (this.props.onSearchFormChanged != null) {
+      const keyword = this.state.keyword;
+      this.props.onSearchFormChanged({ keyword });
+      this.setState({ searchedKeyword: keyword });
+    }
+    else {
+      throw new Error('onSearchFormChanged method is null');
+    }
   }
   }
 
 
   onInputChange(input) { // for only submitting with button
   onInputChange(input) { // for only submitting with button
@@ -32,17 +40,29 @@ class SearchPageForm extends React.Component {
 
 
   render() {
   render() {
     return (
     return (
-      <div className="input-group mb-3 d-flex">
-        <div className="flex-fill">
+      // TODO: modify design after other component is created
+      <div className="grw-search-form-in-search-result-page d-flex">
+        <div className="input-group flex-nowrap">
           <SearchForm
           <SearchForm
-            t={this.props.t}
             onSubmit={this.search}
             onSubmit={this.search}
             keyword={this.state.searchedKeyword}
             keyword={this.state.searchedKeyword}
             onInputChange={this.onInputChange}
             onInputChange={this.onInputChange}
           />
           />
         </div>
         </div>
         <div className="input-group-append">
         <div className="input-group-append">
-          <button className="btn btn-secondary" type="button" id="button-addon2" onClick={this.search}>
+          <button
+            className="btn btn-secondary"
+            type="button"
+            id="button-addon2"
+            onClick={() => {
+              try {
+                this.search();
+              }
+              catch (error) {
+                logger.error(error);
+              }
+            }}
+          >
             <i className="icon-magnifier"></i>
             <i className="icon-magnifier"></i>
           </button>
           </button>
         </div>
         </div>
@@ -58,11 +78,10 @@ class SearchPageForm extends React.Component {
 const SearchPageFormWrapper = withUnstatedContainers(SearchPageForm, [AppContainer]);
 const SearchPageFormWrapper = withUnstatedContainers(SearchPageForm, [AppContainer]);
 
 
 SearchPageForm.propTypes = {
 SearchPageForm.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
 
 
   keyword: PropTypes.string,
   keyword: PropTypes.string,
-  onSearchFormChanged: PropTypes.func.isRequired,
+  onSearchFormChanged: PropTypes.func,
 };
 };
 SearchPageForm.defaultProps = {
 SearchPageForm.defaultProps = {
 };
 };

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

@@ -0,0 +1,43 @@
+import React, { FC } from 'react';
+
+type SearchResultMeta = {
+  took : number,
+  total : number,
+  results: number
+}
+
+type Props = {
+  SearchControl: React.FunctionComponent,
+  SearchResultList: React.FunctionComponent,
+  SearchResultContent: React.FunctionComponent,
+  searchResultMeta: SearchResultMeta,
+  searchingKeyword: string
+}
+
+const SearchPageLayout: FC<Props> = (props: Props) => {
+  const { SearchResultList, SearchControl, SearchResultContent } = props;
+  return (
+    <div className="content-main">
+      <div className="search-result row" id="search-result">
+        <div className="col-lg-6  page-list search-result-list pr-0" id="search-result-list">
+          <nav><SearchControl></SearchControl></nav>
+          <div className="d-flex align-items-start justify-content-between mt-1">
+            <div className="search-result-meta">
+              <i className="icon-magnifier" /> Found {props.searchResultMeta.total} pages with &quot;{props.searchingKeyword}&quot;
+            </div>
+          </div>
+
+          <div className="page-list">
+            <ul className="page-list-ul page-list-ul-flat nav nav-pills"><SearchResultList></SearchResultList></ul>
+          </div>
+        </div>
+        <div className="col-lg-6 d-none d-lg-block search-result-content">
+          <SearchResultContent></SearchResultContent>
+        </div>
+      </div>
+    </div>
+  );
+};
+
+
+export default SearchPageLayout;

+ 0 - 350
packages/app/src/components/SearchPage/SearchResult.jsx

@@ -1,350 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-import * as toastr from 'toastr';
-
-import { withTranslation } from 'react-i18next';
-
-import Page from '../PageList/Page';
-import SearchResultList from './SearchResultList';
-import DeletePageListModal from './DeletePageListModal';
-import AppContainer from '~/client/services/AppContainer';
-import { withUnstatedContainers } from '../UnstatedUtils';
-
-class SearchResult extends React.Component {
-
-  constructor(props) {
-    super(props);
-    this.state = {
-      deletionMode: false,
-      selectedPages: new Set(),
-      isDeleteCompletely: undefined,
-      isDeleteConfirmModalShown: false,
-      errorMessageForDeleting: undefined,
-    };
-    this.toggleDeleteCompletely = this.toggleDeleteCompletely.bind(this);
-    this.deleteSelectedPages = this.deleteSelectedPages.bind(this);
-    this.closeDeleteConfirmModal = this.closeDeleteConfirmModal.bind(this);
-  }
-
-  isNotSearchedYet() {
-    return !this.props.searchResultMeta.took;
-  }
-
-  isNotFound() {
-    return this.props.searchingKeyword !== '' && this.props.pages.length === 0;
-  }
-
-  isError() {
-    if (this.props.searchError !== null) {
-      return true;
-    }
-    return false;
-  }
-
-  /**
-   * move the page
-   */
-  visitPageButtonHandler(e) {
-    window.location.href = e.currentTarget.value;
-  }
-
-  /**
-   * toggle checkbox and add (or delete from) selected pages list
-   *
-   * @param {any} page
-   * @memberof SearchResult
-   */
-  toggleCheckbox(page) {
-    if (this.state.selectedPages.has(page)) {
-      this.state.selectedPages.delete(page);
-    }
-    else {
-      this.state.selectedPages.add(page);
-    }
-    this.setState({ isDeleteConfirmModalShown: false });
-    this.setState({ selectedPages: this.state.selectedPages });
-  }
-
-  /**
-   * check and return is all pages selected for delete?
-   *
-   * @returns all pages selected (or not)
-   * @memberof SearchResult
-   */
-  isAllSelected() {
-    return this.state.selectedPages.size === this.props.pages.length;
-  }
-
-  /**
-   * handle checkbox clicking that all pages select for delete
-   *
-   * @memberof SearchResult
-   */
-  handleAllSelect() {
-    if (this.isAllSelected()) {
-      this.state.selectedPages.clear();
-    }
-    else {
-      this.state.selectedPages.clear();
-      this.props.pages.map((page) => {
-        this.state.selectedPages.add(page);
-        return;
-      });
-    }
-    this.setState({ selectedPages: this.state.selectedPages });
-  }
-
-  /**
-   * change deletion mode
-   *
-   * @memberof SearchResult
-   */
-  handleDeletionModeChange() {
-    this.state.selectedPages.clear();
-    this.setState({ deletionMode: !this.state.deletionMode });
-  }
-
-  /**
-   * toggle check delete completely
-   *
-   * @memberof SearchResult
-   */
-  toggleDeleteCompletely() {
-    // request で completely が undefined でないと指定アリと見なされるため
-    this.setState({ isDeleteCompletely: this.state.isDeleteCompletely ? undefined : true });
-  }
-
-  /**
-   * delete selected pages
-   *
-   * @memberof SearchResult
-   */
-  deleteSelectedPages() {
-    const deleteCompletely = this.state.isDeleteCompletely;
-    Promise.all(Array.from(this.state.selectedPages).map((page) => {
-      return new Promise((resolve, reject) => {
-        const pageId = page._id;
-        const revisionId = page.revision._id;
-
-        this.props.appContainer.apiPost('/pages.remove', { page_id: pageId, revision_id: revisionId, completely: deleteCompletely })
-          .then((res) => {
-            if (res.ok) {
-              this.state.selectedPages.delete(page);
-              return resolve();
-            }
-
-            return reject();
-
-          })
-          .catch((err) => {
-            console.log(err.message); // eslint-disable-line no-console
-            this.setState({ errorMessageForDeleting: err.message });
-            return reject();
-          });
-      });
-    }))
-      .then(() => {
-        window.location.reload();
-      })
-      .catch((err) => {
-        toastr.error(err, 'Error occured', {
-          closeButton: true,
-          progressBar: true,
-          newestOnTop: false,
-          showDuration: '100',
-          hideDuration: '100',
-          timeOut: '3000',
-        });
-      });
-  }
-
-  /**
-   * open confirm modal for page selection delete
-   *
-   * @memberof SearchResult
-   */
-  showDeleteConfirmModal() {
-    this.setState({ isDeleteConfirmModalShown: true });
-  }
-
-  /**
-   * close confirm modal for page selection delete
-   *
-   * @memberof SearchResult
-   */
-  closeDeleteConfirmModal() {
-    this.setState({
-      isDeleteConfirmModalShown: false,
-      errorMessageForDeleting: undefined,
-    });
-  }
-
-  renderListView(pages) {
-    return pages.map((page) => {
-      // Add prefix 'id_' in pageId, because scrollspy of bootstrap doesn't work when the first letter of id attr of target component is numeral.
-      const pageId = `#id_${page._id}`;
-      return (
-        <li key={page._id} className="nav-item page-list-li w-100 m-1">
-          <a className="nav-link page-list-link d-flex align-items-baseline" href={pageId}>
-            <Page page={page} noLink />
-            <div className="ml-auto d-flex">
-              { this.state.deletionMode
-                && (
-                  <div className="custom-control custom-checkbox custom-checkbox-danger">
-                    <input
-                      type="checkbox"
-                      id={`page-delete-check-${page._id}`}
-                      className="custom-control-input search-result-list-delete-checkbox"
-                      value={pageId}
-                      checked={this.state.selectedPages.has(page)}
-                      onChange={() => { return this.toggleCheckbox(page) }}
-                    />
-                    <label className="custom-control-label" htmlFor={`page-delete-check-${page._id}`}></label>
-                  </div>
-                )
-              }
-              <div className="page-list-option">
-                <button type="button" className="btn btn-link p-0" value={page.path} onClick={this.visitPageButtonHandler}><i className="icon-login" /></button>
-              </div>
-            </div>
-          </a>
-        </li>
-      );
-    });
-  }
-
-  render() {
-    const { t } = this.props;
-
-    if (this.isError()) {
-      return (
-        <div className="content-main">
-          <i className="searcing fa fa-warning"></i> Error on searching.
-        </div>
-      );
-    }
-
-    if (this.isNotSearchedYet()) {
-      return <div />;
-    }
-
-    if (this.isNotFound()) {
-      let under = '';
-      if (this.props.tree != null) {
-        under = ` under "${this.props.tree}"`;
-      }
-      return (
-        <div className="content-main">
-          <i className="icon-fw icon-info" /> No page found with &quot;{this.props.searchingKeyword}&quot;{under}
-        </div>
-      );
-
-    }
-
-    let deletionModeButtons = '';
-    let allSelectCheck = '';
-
-    if (this.state.deletionMode) {
-      deletionModeButtons = (
-        <div className="btn-group">
-          <button type="button" className="btn btn-outline-secondary btn-sm rounded-pill-weak" onClick={() => { return this.handleDeletionModeChange() }}>
-            <i className="icon-ban" /> {t('search_result.cancel')}
-          </button>
-          <button
-            type="button"
-            className="btn btn-danger btn-sm rounded-pill-weak"
-            onClick={() => { return this.showDeleteConfirmModal() }}
-            disabled={this.state.selectedPages.size === 0}
-          >
-            <i className="icon-trash" /> {t('search_result.delete')}
-          </button>
-        </div>
-      );
-      allSelectCheck = (
-        <div className="custom-control custom-checkbox custom-checkbox-danger">
-          <input
-            id="all-select-check"
-            className="custom-control-input"
-            type="checkbox"
-            onChange={() => { return this.handleAllSelect() }}
-            checked={this.isAllSelected()}
-          />
-          <label className="custom-control-label" htmlFor="all-select-check">&nbsp;{t('search_result.check_all')}</label>
-        </div>
-      );
-    }
-    else {
-      deletionModeButtons = (
-        <div className="btn-group">
-          <button type="button" className="btn btn-outline-secondary rounded-pill btn-sm" onClick={() => { return this.handleDeletionModeChange() }}>
-            <i className="ti-check-box" /> {t('search_result.deletion_mode_btn_lavel')}
-          </button>
-        </div>
-      );
-    }
-
-    const listView = this.renderListView(this.props.pages);
-
-    /*
-    UI あとで考える
-    <span className="search-result-meta">Found: {this.props.searchResultMeta.total} pages with "{this.props.searchingKeyword}"</span>
-    */
-    return (
-      <div className="content-main">
-        <div className="search-result row" id="search-result">
-          <div className="col-lg-4 d-none d-lg-block page-list search-result-list pr-0" id="search-result-list">
-            <nav>
-              <div className="d-flex align-items-start justify-content-between mt-1">
-                <div className="search-result-meta">
-                  <i className="icon-magnifier" /> Found {this.props.searchResultMeta.total} pages with &quot;{this.props.searchingKeyword}&quot;
-                </div>
-                <div className="text-nowrap">
-                  {deletionModeButtons}
-                  {allSelectCheck}
-                </div>
-              </div>
-
-              <div className="page-list">
-                <ul className="page-list-ul page-list-ul-flat nav nav-pills">{listView}</ul>
-              </div>
-            </nav>
-          </div>
-          <div className="col-lg-8 search-result-content" id="search-result-content">
-            <SearchResultList pages={this.props.pages} searchingKeyword={this.props.searchingKeyword} />
-          </div>
-        </div>
-        <DeletePageListModal
-          isShown={this.state.isDeleteConfirmModalShown}
-          pages={Array.from(this.state.selectedPages)}
-          errorMessage={this.state.errorMessageForDeleting}
-          cancel={this.closeDeleteConfirmModal}
-          confirmedToDelete={this.deleteSelectedPages}
-          isDeleteCompletely={this.state.isDeleteCompletely}
-          toggleDeleteCompletely={this.toggleDeleteCompletely}
-        />
-      </div> // content-main
-    );
-  }
-
-}
-
-/**
- * Wrapper component for using unstated
- */
-const SearchResultWrapper = withUnstatedContainers(SearchResult, [AppContainer]);
-
-SearchResult.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  t: PropTypes.func.isRequired, // i18next
-
-  pages: PropTypes.array.isRequired,
-  searchingKeyword: PropTypes.string.isRequired,
-  searchResultMeta: PropTypes.object.isRequired,
-  searchError: PropTypes.object,
-  tree: PropTypes.string,
-};
-SearchResult.defaultProps = {
-  searchError: null,
-};
-
-export default withTranslation()(SearchResultWrapper);

+ 50 - 0
packages/app/src/components/SearchPage/SearchResultContent.tsx

@@ -0,0 +1,50 @@
+import React, { FC } from 'react';
+
+import RevisionLoader from '../Page/RevisionLoader';
+import AppContainer from '../../client/services/AppContainer';
+
+
+type Props ={
+  appContainer: AppContainer,
+  searchingKeyword:string,
+  selectedPage : any,
+}
+const SearchResultContent: FC<Props> = (props: Props) => {
+  // Temporaly workaround for lint error
+  // later needs to be fixed: RevisoinRender to typescriptcomponet
+  const RevisionRenderTypeAny: any = RevisionLoader;
+  const renderPage = (page) => {
+    const growiRenderer = props.appContainer.getRenderer('searchresult');
+    let showTags = false;
+    if (page.tags != null && page.tags.length > 0) { showTags = true }
+    return (
+      <div key={page._id} className="search-result-page mb-5">
+        <h2>
+          <a href={page.path} className="text-break">
+            {page.path}
+          </a>
+          {showTags && (
+            <div className="mt-1 small">
+              <i className="tag-icon icon-tag"></i> {page.tags.join(', ')}
+            </div>
+          )}
+        </h2>
+        <RevisionRenderTypeAny
+          growiRenderer={growiRenderer}
+          pageId={page._id}
+          pagePath={page.path}
+          revisionId={page.revision}
+          highlightKeywords={props.searchingKeyword}
+        />
+      </div>
+    );
+  };
+  const content = renderPage(props.selectedPage);
+  return (
+
+    <div>{content}</div>
+  );
+};
+
+
+export default SearchResultContent;

+ 35 - 48
packages/app/src/components/SearchPage/SearchResultList.jsx

@@ -1,64 +1,51 @@
 import React from 'react';
 import React from 'react';
 import PropTypes from 'prop-types';
 import PropTypes from 'prop-types';
-
-import RevisionLoader from '../Page/RevisionLoader';
-import AppContainer from '~/client/services/AppContainer';
-import { withUnstatedContainers } from '../UnstatedUtils';
+import SearchResultListItem from './SearchResultListItem';
+import PaginationWrapper from '../PaginationWrapper';
 
 
 class SearchResultList extends React.Component {
 class SearchResultList extends React.Component {
 
 
-  constructor(props) {
-    super(props);
-
-    this.growiRenderer = this.props.appContainer.getRenderer('searchresult');
-  }
-
   render() {
   render() {
-    const resultList = this.props.pages.map((page) => {
-      const showTags = (page.tags != null) && (page.tags.length > 0);
-
-      return (
-        // Add prefix 'id_' in id attr, because scrollspy of bootstrap doesn't work when the first letter of id of target component is numeral.
-        <div id={`id_${page._id}`} key={page._id} className="search-result-page mb-5">
-          <h2>
-            <a href={page.path} className="text-break">{page.path}</a>
-            { showTags && (
-              <div className="mt-1 small"><i className="tag-icon icon-tag"></i> {page.tags.join(', ')}</div>
-            )}
-          </h2>
-          <RevisionLoader
-            growiRenderer={this.growiRenderer}
-            pageId={page._id}
-            pagePath={page.path}
-            revisionId={page.revision}
-            highlightKeywords={this.props.searchingKeyword}
-          />
-        </div>
-      );
-    });
-
     return (
     return (
-      <div>
-        {resultList}
-      </div>
+      <>
+        {this.props.pages.map((page) => {
+        // TODO : send cetain length of body (revisionBody) from elastisearch by adding some settings to the query and
+        //         when keyword is not in page content, display revisionBody.
+        // TASK : https://estoc.weseek.co.jp/redmine/issues/79606
+          return (
+            <SearchResultListItem
+              page={page}
+              onClickInvoked={this.props.onClickInvoked}
+              noLink
+            />
+          );
+        })}
+        {this.props.searchResultCount != null && this.props.searchResultCount > 0 && (
+          <div className="my-4 mx-auto">
+            <PaginationWrapper
+              activePage={this.props.activePage}
+              changePage={this.props.onPagingNumberChanged}
+              totalItemsCount={this.props.searchResultCount || 0}
+              pagingLimit={this.props.pagingLimit}
+            />
+          </div>
+        )}
+      </>
     );
     );
   }
   }
 
 
 }
 }
 
 
-/**
- * Wrapper component for using unstated
- */
-const SearchResultListWrapper = withUnstatedContainers(SearchResultList, [AppContainer]);
-
 SearchResultList.propTypes = {
 SearchResultList.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-
   pages: PropTypes.array.isRequired,
   pages: PropTypes.array.isRequired,
-  searchingKeyword: PropTypes.string.isRequired,
-};
-
-SearchResultList.defaultProps = {
+  deletionMode: PropTypes.bool.isRequired,
+  selectedPages: PropTypes.array.isRequired,
+  searchResultCount: PropTypes.number,
+  activePage: PropTypes.number.isRequired,
+  pagingLimit: PropTypes.number,
+  onClickInvoked: PropTypes.func,
+  onChangeInvoked: PropTypes.func,
+  onPagingNumberChanged: PropTypes.func,
 };
 };
 
 
-export default SearchResultListWrapper;
+export default SearchResultList;

+ 99 - 0
packages/app/src/components/SearchPage/SearchResultListItem.tsx

@@ -0,0 +1,99 @@
+import React, { FC } from 'react';
+
+import { UserPicture, PageListMeta, PagePathLabel } from '@growi/ui';
+import { DevidedPagePath } from '@growi/core';
+
+import loggerFactory from '~/utils/logger';
+
+const logger = loggerFactory('growi:searchResultList');
+
+type Props ={
+  page: {
+    _id: string,
+    path: string,
+    noLink: boolean,
+    lastUpdateUser: any
+    elasticSearchResult: {
+      snippet: string,
+    }
+  },
+  onClickInvoked: (data: string) => void,
+}
+
+const SearchResultListItem: FC<Props> = (props:Props) => {
+
+  const { page, onClickInvoked } = props;
+
+  // Add prefix 'id_' in pageId, because scrollspy of bootstrap doesn't work when the first letter of id attr of target component is numeral.
+  const pageId = `#${page._id}`;
+
+  const dPagePath = new DevidedPagePath(page.path, false, true);
+  const pagePathElem = <PagePathLabel page={page} isFormerOnly />;
+
+  // TODO : send cetain  length of body (revisionBody) from elastisearch by adding some settings to the query and
+  //         when keyword is not in page content, display revisionBody.
+  // TASK : https://estoc.weseek.co.jp/redmine/issues/79606
+
+  return (
+    <li key={page._id} className="page-list-li w-100 border-bottom pr-4">
+      <a
+        className="d-block pt-3"
+        href={pageId}
+        onClick={() => {
+          try {
+            if (onClickInvoked == null) { throw new Error('onClickInvoked is null') }
+            onClickInvoked(page._id);
+          }
+          catch (error) {
+            logger.error(error);
+          }
+        }}
+      >
+        <div className="d-flex">
+          {/* checkbox */}
+          <div className="form-check my-auto mx-2">
+            <input className="form-check-input my-auto" type="checkbox" value="" id="flexCheckDefault" />
+          </div>
+          <div className="w-100">
+            {/* page path */}
+            <small className="mb-1">
+              <i className="icon-fw icon-home"></i>
+              {pagePathElem}
+            </small>
+            <div className="d-flex my-1 align-items-center">
+              {/* page title */}
+              <h3 className="mb-0">
+                <UserPicture user={page.lastUpdateUser} />
+                <span className="mx-2">{dPagePath.latter}</span>
+              </h3>
+              {/* page meta */}
+              <div className="d-flex mx-2">
+                <PageListMeta page={page} />
+              </div>
+              {/* doropdown icon */}
+              <div className="ml-auto">
+                <i className="fa fa-ellipsis-v text-muted"></i>
+              </div>
+
+              {/* Todo: add the following icon into dropdown menu */}
+              {/* <button
+                type="button"
+                className="btn btn-link p-0"
+                value={page.path}
+                onClick={(e) => {
+                  window.location.href = e.currentTarget.value;
+                }}
+              >
+                <i className="icon-login" />
+              </button> */}
+
+            </div>
+            {/* eslint-disable-next-line react/no-danger */}
+            <div className="mt-1" dangerouslySetInnerHTML={{ __html: page.elasticSearchResult.snippet }}></div>
+          </div>
+        </div>
+      </a>
+    </li>
+  );
+};
+export default SearchResultListItem;

+ 3 - 1
packages/app/src/server/events/page.js

@@ -18,5 +18,7 @@ PageEvent.prototype.onUpdate = function(page, user) {
 PageEvent.prototype.onCreateMany = function(pages, user) {
 PageEvent.prototype.onCreateMany = function(pages, user) {
   debug('onCreateMany event fired');
   debug('onCreateMany event fired');
 };
 };
-
+PageEvent.prototype.onAddSeenUsers = function(pages, user) {
+  debug('onAddSeenUsers event fired');
+};
 module.exports = PageEvent;
 module.exports = PageEvent;

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

@@ -288,6 +288,7 @@ module.exports = function(crowi) {
     pageEvent.on('create', pageEvent.onCreate);
     pageEvent.on('create', pageEvent.onCreate);
     pageEvent.on('update', pageEvent.onUpdate);
     pageEvent.on('update', pageEvent.onUpdate);
     pageEvent.on('createMany', pageEvent.onCreateMany);
     pageEvent.on('createMany', pageEvent.onCreateMany);
+    pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
   }
   }
 
 
   function validateCrowi() {
   function validateCrowi() {
@@ -413,6 +414,7 @@ module.exports = function(crowi) {
     const saved = await this.save();
     const saved = await this.save();
 
 
     debug('seenUsers updated!', added);
     debug('seenUsers updated!', added);
+    pageEvent.emit('addSeenUsers', saved);
 
 
     return saved;
     return saved;
   };
   };

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

@@ -139,7 +139,9 @@ module.exports = function(crowi, app) {
 
 
     const result = {};
     const result = {};
     try {
     try {
-      const esResult = await searchService.searchKeyword(keyword, user, userGroups, searchOpts);
+      const esResult = searchService.formatResult(
+        await searchService.searchKeyword(keyword, user, userGroups, searchOpts),
+      );
 
 
       // create score map for sorting
       // create score map for sorting
       // key: id , value: score
       // key: id , value: score
@@ -150,11 +152,13 @@ module.exports = function(crowi, app) {
 
 
       const ids = esResult.data.map((page) => { return page._id });
       const ids = esResult.data.map((page) => { return page._id });
       const findResult = await Page.findListByPageIds(ids);
       const findResult = await Page.findListByPageIds(ids);
-
-      // add tag data to result pages
+      // add tags and elasticSearch data to page
       findResult.pages.map((page) => {
       findResult.pages.map((page) => {
-        const data = esResult.data.find((data) => { return page.id === data._id });
+        const data = esResult.data.find((data) => {
+          return page.id === data._id;
+        });
         page._doc.tags = data._source.tag_names;
         page._doc.tags = data._source.tag_names;
+        page._doc.elasticSearchResult = data.elasticSearchResult;
         return page;
         return page;
       });
       });
 
 

+ 1 - 0
packages/app/src/server/service/page.js

@@ -25,6 +25,7 @@ class PageService {
     this.pageEvent.on('create', this.pageEvent.onCreate);
     this.pageEvent.on('create', this.pageEvent.onCreate);
     this.pageEvent.on('update', this.pageEvent.onUpdate);
     this.pageEvent.on('update', this.pageEvent.onUpdate);
     this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
     this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
+    this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
   }
   }
 
 
   /**
   /**

+ 24 - 4
packages/app/src/server/service/search-delegator/elasticsearch.js

@@ -309,6 +309,7 @@ class ElasticsearchDelegator {
     };
     };
 
 
     const bookmarkCount = page.bookmarkCount || 0;
     const bookmarkCount = page.bookmarkCount || 0;
+    const seenUsersCount = page.seenUsers.length || 0;
     let document = {
     let document = {
       path: page.path,
       path: page.path,
       body: page.revision.body,
       body: page.revision.body,
@@ -316,6 +317,7 @@ class ElasticsearchDelegator {
       username: page.creator != null ? page.creator.username : null,
       username: page.creator != null ? page.creator.username : null,
       comment_count: page.commentCount,
       comment_count: page.commentCount,
       bookmark_count: bookmarkCount,
       bookmark_count: bookmarkCount,
+      seenUsers_count: seenUsersCount,
       like_count: page.liker.length || 0,
       like_count: page.liker.length || 0,
       created_at: page.createdAt,
       created_at: page.createdAt,
       updated_at: page.updatedAt,
       updated_at: page.updatedAt,
@@ -551,14 +553,19 @@ class ElasticsearchDelegator {
         results: result.hits.hits.length,
         results: result.hits.hits.length,
       },
       },
       data: result.hits.hits.map((elm) => {
       data: result.hits.hits.map((elm) => {
-        return { _id: elm._id, _score: elm._score, _source: elm._source };
+        return {
+          _id: elm._id,
+          _score: elm._score,
+          _source: elm._source,
+          _highlight: elm.highlight,
+        };
       }),
       }),
     };
     };
   }
   }
 
 
   createSearchQuerySortedByUpdatedAt(option) {
   createSearchQuerySortedByUpdatedAt(option) {
     // getting path by default is almost for debug
     // getting path by default is almost for debug
-    let fields = ['path', 'bookmark_count', 'comment_count', 'updated_at', 'tag_names'];
+    let fields = ['path', 'bookmark_count', 'comment_count', 'seenUsers_count', 'updated_at', 'tag_names'];
     if (option) {
     if (option) {
       fields = option.fields || fields;
       fields = option.fields || fields;
     }
     }
@@ -579,7 +586,7 @@ class ElasticsearchDelegator {
   }
   }
 
 
   createSearchQuerySortedByScore(option) {
   createSearchQuerySortedByScore(option) {
-    let fields = ['path', 'bookmark_count', 'comment_count', 'updated_at', 'tag_names'];
+    let fields = ['path', 'bookmark_count', 'comment_count', 'seenUsers_count', 'updated_at', 'tag_names'];
     if (option) {
     if (option) {
       fields = option.fields || fields;
       fields = option.fields || fields;
     }
     }
@@ -856,6 +863,19 @@ class ElasticsearchDelegator {
     };
     };
   }
   }
 
 
+  appendHighlight(query) {
+    query.body.highlight = {
+      fields: {
+        '*': {
+          fragment_size: 40,
+          fragmenter: 'simple',
+          pre_tags: ["<em class='highlighted-keyword'>"],
+          post_tags: ['</em>'],
+        },
+      },
+    };
+  }
+
   async searchKeyword(queryString, user, userGroups, option) {
   async searchKeyword(queryString, user, userGroups, option) {
     const from = option.offset || null;
     const from = option.offset || null;
     const size = option.limit || null;
     const size = option.limit || null;
@@ -869,7 +889,7 @@ class ElasticsearchDelegator {
     this.appendResultSize(query, from, size);
     this.appendResultSize(query, from, size);
 
 
     this.appendFunctionScore(query, queryString);
     this.appendFunctionScore(query, queryString);
-
+    this.appendHighlight(query);
     return this.search(query);
     return this.search(query);
   }
   }
 
 

+ 29 - 0
packages/app/src/server/service/search.js

@@ -2,6 +2,16 @@ import loggerFactory from '~/utils/logger';
 
 
 // eslint-disable-next-line no-unused-vars
 // eslint-disable-next-line no-unused-vars
 const logger = loggerFactory('growi:service:search');
 const logger = loggerFactory('growi:service:search');
+const xss = require('xss');
+
+// options for filtering xss
+const filterXssOptions = {
+  whiteList: {
+    em: ['class'],
+  },
+};
+
+const filterXss = new xss.FilterXSS(filterXssOptions);
 
 
 class SearchService {
 class SearchService {
 
 
@@ -68,6 +78,7 @@ class SearchService {
     pageEvent.on('delete', this.delegator.syncPageDeleted.bind(this.delegator));
     pageEvent.on('delete', this.delegator.syncPageDeleted.bind(this.delegator));
     pageEvent.on('updateMany', this.delegator.syncPagesUpdated.bind(this.delegator));
     pageEvent.on('updateMany', this.delegator.syncPagesUpdated.bind(this.delegator));
     pageEvent.on('syncDescendants', this.delegator.syncDescendantsPagesUpdated.bind(this.delegator));
     pageEvent.on('syncDescendants', this.delegator.syncDescendantsPagesUpdated.bind(this.delegator));
+    pageEvent.on('addSeenUsers', this.delegator.syncPageUpdated.bind(this.delegator));
 
 
     const bookmarkEvent = this.crowi.event('bookmark');
     const bookmarkEvent = this.crowi.event('bookmark');
     bookmarkEvent.on('create', this.delegator.syncBookmarkChanged.bind(this.delegator));
     bookmarkEvent.on('create', this.delegator.syncBookmarkChanged.bind(this.delegator));
@@ -148,6 +159,24 @@ class SearchService {
     }
     }
   }
   }
 
 
+  /**
+   * formatting result
+   */
+  formatResult(esResult) {
+    esResult.data.forEach((data) => {
+      const highlightData = data._highlight;
+      const snippet = highlightData['body.en'] || highlightData['body.ja'] || '';
+      const pathMatch = highlightData['path.en'] || highlightData['path.ja'] || '';
+
+      data.elasticSearchResult = {
+        snippet: filterXss.process(snippet),
+        // todo: use filter xss.process() for matchedPath;
+        matchedPath: pathMatch,
+      };
+    });
+    return esResult;
+  }
+
 }
 }
 
 
 module.exports = SearchService;
 module.exports = SearchService;

+ 3 - 1
packages/app/src/styles/_search.scss

@@ -165,6 +165,7 @@
     .nav.nav-pills {
     .nav.nav-pills {
       > li {
       > li {
         > a {
         > a {
+          height: 123px;
           padding: 2px 8px;
           padding: 2px 8px;
           word-break: break-all;
           word-break: break-all;
           border-radius: 0;
           border-radius: 0;
@@ -175,7 +176,7 @@
           }
           }
           &.active {
           &.active {
             padding-right: 5px;
             padding-right: 5px;
-            border-right: solid 3px transparent;
+            border-left: solid 3px transparent;
           }
           }
           > * {
           > * {
             margin-right: 3px;
             margin-right: 3px;
@@ -222,6 +223,7 @@
   }
   }
 }
 }
 
 
+// 2021/9/22 TODO: Remove after moving to SearchResult
 .search-page-input {
 .search-page-input {
   position: sticky;
   position: sticky;
   top: 15px;
   top: 15px;

+ 3 - 0
packages/app/src/styles/theme/_apply-colors.scss

@@ -587,6 +587,9 @@ body.pathname-sidebar {
 .search-result {
 .search-result {
   .search-result-list {
   .search-result-list {
     .page-list {
     .page-list {
+      .highlighted-keyword {
+        background-color: $bgcolor-keyword-highlighted;
+      }
       .page-list-ul {
       .page-list-ul {
         > li.nav-item > a.nav-link {
         > li.nav-item > a.nav-link {
           color: inherit;
           color: inherit;

+ 8 - 0
packages/ui/src/components/PagePath/PagePathLabel.jsx

@@ -14,6 +14,13 @@ export const PagePathLabel = (props) => {
     return <span className={classNames.join(' ')}>{dPagePath.latter}</span>;
     return <span className={classNames.join(' ')}>{dPagePath.latter}</span>;
   }
   }
 
 
+  if (props.isFormerOnly) {
+    const textElem = dPagePath.isFormerRoot
+      ? <>/</>
+      : <>{dPagePath.former}</>;
+    return <span className={classNames.join(' ')}>{textElem}</span>;
+  }
+
   const textElem = dPagePath.isRoot
   const textElem = dPagePath.isRoot
     ? <><strong>/</strong></>
     ? <><strong>/</strong></>
     : <>{dPagePath.former}/<strong>{dPagePath.latter}</strong></>;
     : <>{dPagePath.former}/<strong>{dPagePath.latter}</strong></>;
@@ -24,6 +31,7 @@ export const PagePathLabel = (props) => {
 PagePathLabel.propTypes = {
 PagePathLabel.propTypes = {
   page: PropTypes.object.isRequired,
   page: PropTypes.object.isRequired,
   isLatterOnly: PropTypes.bool,
   isLatterOnly: PropTypes.bool,
+  isFormerOnly: PropTypes.bool,
   additionalClassNames: PropTypes.arrayOf(PropTypes.string),
   additionalClassNames: PropTypes.arrayOf(PropTypes.string),
 };
 };