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

Merge pull request #3416 from weseek/master

release v4.2.9
Yuki Takei 5 лет назад
Родитель
Сommit
7f755bc4f8
37 измененных файлов с 732 добавлено и 455 удалено
  1. 10 1
      CHANGES.md
  2. 1 1
      package.json
  3. 16 4
      resource/locales/en_US/translation.json
  4. 16 4
      resource/locales/ja_JP/translation.json
  5. 17 5
      resource/locales/zh_CN/translation.json
  6. 11 1
      src/client/js/app.jsx
  7. 2 2
      src/client/js/components/Page/DisplaySwitcher.jsx
  8. 3 1
      src/client/js/components/Page/DuplicatedAlert.jsx
  9. 3 1
      src/client/js/components/Page/RedirectedAlert.jsx
  10. 3 1
      src/client/js/components/Page/RenamedAlert.jsx
  11. 5 1
      src/client/js/components/PageAccessories.jsx
  12. 8 6
      src/client/js/components/PageAccessoriesModal.jsx
  13. 16 6
      src/client/js/components/PageAccessoriesModalControl.jsx
  14. 20 10
      src/client/js/components/PageHistory.jsx
  15. 0 133
      src/client/js/components/PageHistory/PageRevisionList.jsx
  16. 165 0
      src/client/js/components/PageHistory/PageRevisionTable.jsx
  17. 15 45
      src/client/js/components/PageHistory/Revision.jsx
  18. 32 3
      src/client/js/components/PageHistory/RevisionDiff.jsx
  19. 116 0
      src/client/js/components/RevisionComparer/RevisionComparer.jsx
  20. 3 0
      src/client/js/services/EditorContainer.js
  21. 10 12
      src/client/js/services/PageHistoryContainer.js
  22. 112 0
      src/client/js/services/RevisionComparerContainer.js
  23. 4 0
      src/client/styles/scss/_page-accessories-modal.scss
  24. 58 0
      src/client/styles/scss/_page-history.scss
  25. 0 68
      src/client/styles/scss/_page.scss
  26. 1 0
      src/client/styles/scss/style-app.scss
  27. 4 41
      src/server/models/page.js
  28. 4 2
      src/server/routes/apiv3/app-settings.js
  29. 1 1
      src/server/routes/apiv3/pages.js
  30. 11 1
      src/server/routes/apiv3/revisions.js
  31. 15 19
      src/server/routes/comment.js
  32. 24 51
      src/server/routes/page.js
  33. 5 5
      src/server/service/page.js
  34. 1 1
      src/server/service/search-delegator/elasticsearch.js
  35. 14 4
      src/server/service/user-notification/index.js
  36. 2 2
      src/server/views/widget/page_content.html
  37. 4 23
      src/test/models/page.test.js

+ 10 - 1
CHANGES.md

@@ -1,6 +1,15 @@
 # CHANGES
 # CHANGES
 
 
-## v4.2.8-RC
+## v4.2.9-RC
+
+* Feature: Comparing revisions
+* Improvement: Memory consumption when re-indexing for full text searching
+* Improvement: Site URL settings valildation
+* Fix: Show comfirmation when transiting page without save
+* Fix: Save slack channels history when user trigger notification is invoked
+* Fix: The label of alerts for move/rename/delete are borken
+
+## v4.2.8
 
 
 * Improvement: Performance for pages to rename/duplicate/delete/revert pages
 * Improvement: Performance for pages to rename/duplicate/delete/revert pages
 * Fix: Preview scrollbar doesn't sync to editor
 * Fix: Preview scrollbar doesn't sync to editor

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "growi",
   "name": "growi",
-  "version": "4.2.8-RC",
+  "version": "4.2.9-RC",
   "description": "Team collaboration software using markdown",
   "description": "Team collaboration software using markdown",
   "tags": [
   "tags": [
     "wiki",
     "wiki",

+ 16 - 4
resource/locales/en_US/translation.json

@@ -76,7 +76,6 @@
   "Go to this version": "View this version",
   "Go to this version": "View this version",
   "View diff": "View diff",
   "View diff": "View diff",
   "No diff": "No diff",
   "No diff": "No diff",
-  "Shrink versions that have no diffs": "Shrink versions that have no diffs",
   "User ID": "User ID",
   "User ID": "User ID",
   "User Information": "User information",
   "User Information": "User information",
   "Basic Info": "Basic info",
   "Basic Info": "Basic info",
@@ -166,6 +165,7 @@
   },
   },
   "not_found_page": {
   "not_found_page": {
     "Create Page": "Create Page",
     "Create Page": "Create Page",
+    "page_not_exist": "This page does not exist.",
     "page_not_exist_alert": "This page does not exist. Please create a new page."
     "page_not_exist_alert": "This page does not exist. Please create a new page."
   },
   },
   "custom_navigation": {
   "custom_navigation": {
@@ -292,9 +292,12 @@
   "page_page": {
   "page_page": {
     "notice": {
     "notice": {
       "version": "This is not the current version.",
       "version": "This is not the current version.",
-      "moved": "This page was moved from <code>%s</code>",
-      "redirected": "You are redirected from <code>%s</code>",
-      "duplicated": "This page was duplicated from <code>%s</code>",
+      "moved": "This page was moved from",
+      "moved_period": ".",
+      "redirected": "You are redirected from",
+      "redirected_period": ".",
+      "duplicated": "This page was duplicated from",
+      "duplicated_period": ".",
       "unlinked": "Redirect pages to this page have been deleted.",
       "unlinked": "Redirect pages to this page have been deleted.",
       "restricted": "Access to this page is restricted",
       "restricted": "Access to this page is restricted",
       "stale": "More than {{count}} year has passed since last update.",
       "stale": "More than {{count}} year has passed since last update.",
@@ -323,6 +326,15 @@
     "outdated": "Page is updated someone and now outdated.",
     "outdated": "Page is updated someone and now outdated.",
     "user_not_admin": "Only admin user can delete completely"
     "user_not_admin": "Only admin user can delete completely"
   },
   },
+  "page_history": {
+    "revision_list": "Revision list",
+    "revision": "version",
+    "comparing_source": "Source",
+    "comparing_target": "Target",
+    "comparing_revisions": "Comparing the difference",
+    "compare_latest":"Compare latest revision",
+    "compare_previous":"Compare previous revision"
+  },
   "modal_rename": {
   "modal_rename": {
     "label": {
     "label": {
       "Move/Rename page": "Move/Rename page",
       "Move/Rename page": "Move/Rename page",

+ 16 - 4
resource/locales/ja_JP/translation.json

@@ -77,7 +77,6 @@
   "Go to this version": "このバージョンを見る",
   "Go to this version": "このバージョンを見る",
   "View diff": "差分を表示",
   "View diff": "差分を表示",
   "No diff": "差分なし",
   "No diff": "差分なし",
-  "Shrink versions that have no diffs": "差分のないバージョンをコンパクトに表示する",
   "User ID": "ユーザーID",
   "User ID": "ユーザーID",
   "User Information": "ユーザー情報",
   "User Information": "ユーザー情報",
   "Basic Info": "ユーザーの基本情報",
   "Basic Info": "ユーザーの基本情報",
@@ -169,6 +168,7 @@
   },
   },
   "not_found_page": {
   "not_found_page": {
     "Create Page": "ページを作成する",
     "Create Page": "ページを作成する",
+    "page_not_exist": "このページは存在しません。",
     "page_not_exist_alert": "このページは存在しません。新たに作成する必要があります。"
     "page_not_exist_alert": "このページは存在しません。新たに作成する必要があります。"
   },
   },
   "custom_navigation": {
   "custom_navigation": {
@@ -295,9 +295,12 @@
   "page_page": {
   "page_page": {
     "notice": {
     "notice": {
       "version": "これは現在の版ではありません。",
       "version": "これは現在の版ではありません。",
-      "moved": "このページは <code>%s</code> から移動しました。",
-      "redirected": "リダイレクト元 >> <code>%s</code>",
-      "duplicated": "このページは <code>%s</code> から複製されました。",
+      "moved": "このページは",
+      "moved_period":"から移動しました。",
+      "redirected": "リダイレクト元 >>",
+      "redirected_period":"",
+      "duplicated": "このページは",
+      "duplicated_period": "から複製されました。",
       "unlinked": "このページへのリダイレクトは削除されました。",
       "unlinked": "このページへのリダイレクトは削除されました。",
       "restricted": "このページの閲覧は制限されています",
       "restricted": "このページの閲覧は制限されています",
       "stale": "このページは最終更新日から{{count}}年以上が経過しています。",
       "stale": "このページは最終更新日から{{count}}年以上が経過しています。",
@@ -325,6 +328,15 @@
     "outdated": "ページが他のユーザーによって更新されました。",
     "outdated": "ページが他のユーザーによって更新されました。",
     "user_not_admin": "権限のあるユーザーのみが完全削除できます"
     "user_not_admin": "権限のあるユーザーのみが完全削除できます"
   },
   },
+  "page_history": {
+    "revision_list": "更新履歴",
+    "revision": "バージョン",
+    "comparing_source": "ソース",
+    "comparing_target": "ターゲット",
+    "comparing_revisions": "差分を比較する",
+    "compare_latest":"最新と比較",
+    "compare_previous":"1つ前のバージョンと比較"
+  },
   "modal_rename": {
   "modal_rename": {
     "label": {
     "label": {
       "Move/Rename page": "ページを移動/名前変更する",
       "Move/Rename page": "ページを移動/名前変更する",

+ 17 - 5
resource/locales/zh_CN/translation.json

@@ -80,7 +80,6 @@
 	"Go to this version": "查看此版本",
 	"Go to this version": "查看此版本",
 	"View diff": "查看差异",
 	"View diff": "查看差异",
 	"No diff": "无差异",
 	"No diff": "无差异",
-	"Shrink versions that have no diffs": "收缩没有差异的版本",
 	"User ID": "用户ID",
 	"User ID": "用户ID",
 	"Home": "首页",
 	"Home": "首页",
 	"My Drafts": "My Drafts",
 	"My Drafts": "My Drafts",
@@ -167,6 +166,7 @@
   },
   },
   "not_found_page": {
   "not_found_page": {
     "Create Page": "创建页面",
     "Create Page": "创建页面",
+    "page_not_exist": "该页面不存在",
     "page_not_exist_alert": "该页面不存在,请创建一个新页面"
     "page_not_exist_alert": "该页面不存在,请创建一个新页面"
   },
   },
   "custom_navigation": {
   "custom_navigation": {
@@ -274,9 +274,12 @@
 	"page_page": {
 	"page_page": {
 		"notice": {
 		"notice": {
 			"version": "这不是当前版本。",
 			"version": "这不是当前版本。",
-			"moved": "此页已从<code>%s</code>",
-			"redirected": "您将从<code>%s</code>",
-			"duplicated": "此页来自<code>%s</code>",
+			"moved": "此页已从",
+      "moved_period": "",
+			"redirected": "您将从",
+      "redirected_period": "",
+			"duplicated": "此页来自",
+      "duplicated_period": "",
 			"unlinked": "将网页重定向到此网页已被删除。",
 			"unlinked": "将网页重定向到此网页已被删除。",
 			"restricted": "访问此页受到限制",
 			"restricted": "访问此页受到限制",
 			"stale": "自上次更新以来,已超过{{count}年。",
 			"stale": "自上次更新以来,已超过{{count}年。",
@@ -303,7 +306,16 @@
 		"already_exists": "新建页面已存在",
 		"already_exists": "新建页面已存在",
 		"outdated": "页面已被某人更新,现在已过时。",
 		"outdated": "页面已被某人更新,现在已过时。",
 		"user_not_admin": "仅管理员用户可以完全删除"
 		"user_not_admin": "仅管理员用户可以完全删除"
-	},
+  },
+  "page_history": {
+    "revision_list": "修订清单",
+    "revision": "版本",
+    "comparing_source": "源头",
+    "comparing_target": "目标",
+    "comparing_revisions": "比较两者的区别",
+    "compare_latest":"比較最新版本",
+    "compare_previous":"比較以前的版本"
+  },
 	"modal_rename": {
 	"modal_rename": {
 		"label": {
 		"label": {
 			"Move/Rename page": "页面 移动/重命名",
 			"Move/Rename page": "页面 移动/重命名",

+ 11 - 1
src/client/js/app.jsx

@@ -40,10 +40,12 @@ import GrowiSubNavigationSwitcher from './components/Navbar/GrowiSubNavigationSw
 import NavigationContainer from './services/NavigationContainer';
 import NavigationContainer from './services/NavigationContainer';
 import PageContainer from './services/PageContainer';
 import PageContainer from './services/PageContainer';
 import PageHistoryContainer from './services/PageHistoryContainer';
 import PageHistoryContainer from './services/PageHistoryContainer';
+import RevisionComparerContainer from './services/RevisionComparerContainer';
 import CommentContainer from './services/CommentContainer';
 import CommentContainer from './services/CommentContainer';
 import EditorContainer from './services/EditorContainer';
 import EditorContainer from './services/EditorContainer';
 import TagContainer from './services/TagContainer';
 import TagContainer from './services/TagContainer';
 import PersonalContainer from './services/PersonalContainer';
 import PersonalContainer from './services/PersonalContainer';
+import PageAccessoriesContainer from './services/PageAccessoriesContainer';
 
 
 import { appContainer, componentMappings } from './base';
 import { appContainer, componentMappings } from './base';
 
 
@@ -58,12 +60,15 @@ const socketIoContainer = appContainer.getContainer('SocketIoContainer');
 const navigationContainer = new NavigationContainer(appContainer);
 const navigationContainer = new NavigationContainer(appContainer);
 const pageContainer = new PageContainer(appContainer);
 const pageContainer = new PageContainer(appContainer);
 const pageHistoryContainer = new PageHistoryContainer(appContainer, pageContainer);
 const pageHistoryContainer = new PageHistoryContainer(appContainer, pageContainer);
+const revisionComparerContainer = new RevisionComparerContainer(appContainer, pageContainer);
 const commentContainer = new CommentContainer(appContainer);
 const commentContainer = new CommentContainer(appContainer);
 const editorContainer = new EditorContainer(appContainer, defaultEditorOptions, defaultPreviewOptions);
 const editorContainer = new EditorContainer(appContainer, defaultEditorOptions, defaultPreviewOptions);
 const tagContainer = new TagContainer(appContainer);
 const tagContainer = new TagContainer(appContainer);
 const personalContainer = new PersonalContainer(appContainer);
 const personalContainer = new PersonalContainer(appContainer);
+const pageAccessoriesContainer = new PageAccessoriesContainer(appContainer);
 const injectableContainers = [
 const injectableContainers = [
-  appContainer, socketIoContainer, navigationContainer, pageContainer, pageHistoryContainer, commentContainer, editorContainer, tagContainer, personalContainer,
+  appContainer, socketIoContainer, navigationContainer, pageContainer, pageHistoryContainer, revisionComparerContainer,
+  commentContainer, editorContainer, tagContainer, personalContainer, pageAccessoriesContainer,
 ];
 ];
 
 
 logger.info('unstated containers have been initialized');
 logger.info('unstated containers have been initialized');
@@ -120,6 +125,11 @@ if (pageContainer.state.pageId != null) {
     'recent-created-icon': <RecentlyCreatedIcon />,
     'recent-created-icon': <RecentlyCreatedIcon />,
     'user-bookmark-icon': <BookmarkIcon />,
     'user-bookmark-icon': <BookmarkIcon />,
   });
   });
+
+  // show the Page accessory modal when query of "compare" is requested
+  if (revisionComparerContainer.getRevisionIDsToCompareAsParam().length > 0) {
+    pageAccessoriesContainer.openPageAccessoriesModal('pageHistory');
+  }
 }
 }
 if (pageContainer.state.creator != null) {
 if (pageContainer.state.creator != null) {
   Object.assign(componentMappings, {
   Object.assign(componentMappings, {

+ 2 - 2
src/client/js/components/Page/DisplaySwitcher.jsx

@@ -19,7 +19,7 @@ const DisplaySwitcher = (props) => {
     navigationContainer, pageContainer,
     navigationContainer, pageContainer,
   } = props;
   } = props;
   const { editorMode } = navigationContainer.state;
   const { editorMode } = navigationContainer.state;
-  const { pageUser } = pageContainer.state;
+  const { isPageExist, pageUser } = pageContainer.state;
 
 
   return (
   return (
     <>
     <>
@@ -30,7 +30,7 @@ const DisplaySwitcher = (props) => {
             <div className="grw-side-contents-container">
             <div className="grw-side-contents-container">
               <div className="grw-side-contents-sticky-container">
               <div className="grw-side-contents-sticky-container">
                 <div className="border-bottom pb-1">
                 <div className="border-bottom pb-1">
-                  <PageAccessories />
+                  <PageAccessories isNotFoundPage={!isPageExist} />
                 </div>
                 </div>
 
 
                 <div className="d-none d-lg-block">
                 <div className="d-none d-lg-block">

+ 3 - 1
src/client/js/components/Page/DuplicatedAlert.jsx

@@ -5,11 +5,13 @@ import { withTranslation } from 'react-i18next';
 
 
 const DuplicatedAlert = (props) => {
 const DuplicatedAlert = (props) => {
   const { t } = props;
   const { t } = props;
+  const urlParams = new URLSearchParams(window.location.search);
+  const fromPath = urlParams.get('duplicated');
 
 
   return (
   return (
     <div className="alert alert-success py-3 px-4">
     <div className="alert alert-success py-3 px-4">
       <strong>
       <strong>
-        { t('Duplicated') }:{t('page_page.notice.duplicated')}
+        { t('Duplicated') }: {t('page_page.notice.duplicated')} <code>{fromPath}</code> {t('page_page.notice.duplicated_period')}
       </strong>
       </strong>
     </div>
     </div>
   );
   );

+ 3 - 1
src/client/js/components/Page/RedirectedAlert.jsx

@@ -5,10 +5,12 @@ import { withTranslation } from 'react-i18next';
 
 
 const RedirectedAlert = (props) => {
 const RedirectedAlert = (props) => {
   const { t } = props;
   const { t } = props;
+  const urlParams = new URLSearchParams(window.location.search);
+  const fromPath = urlParams.get('redirectFrom');
 
 
   return (
   return (
     <>
     <>
-      <strong>{ t('Redirected') }:</strong>{ t('page_page.notice.redirected')}
+      <strong>{ t('Redirected') }:</strong> { t('page_page.notice.redirected')} <code>{fromPath}</code> {t('page_page.notice.redirected_period')}
     </>
     </>
   );
   );
 };
 };

+ 3 - 1
src/client/js/components/Page/RenamedAlert.jsx

@@ -5,10 +5,12 @@ import { withTranslation } from 'react-i18next';
 
 
 const RenamedAlert = (props) => {
 const RenamedAlert = (props) => {
   const { t } = props;
   const { t } = props;
+  const urlParams = new URLSearchParams(window.location.search);
+  const fromPath = urlParams.get('renamedFrom');
 
 
   return (
   return (
     <>
     <>
-      <strong>{ t('Moved') }:</strong>{t('page_page.notice.moved')}
+      <strong>{ t('Moved') }:</strong> {t('page_page.notice.moved')} <code>{fromPath}</code> {t('page_page.notice.moved_period')}
     </>
     </>
   );
   );
 };
 };

+ 5 - 1
src/client/js/components/PageAccessories.jsx

@@ -9,7 +9,7 @@ import AppContainer from '../services/AppContainer';
 import PageAccessoriesContainer from '../services/PageAccessoriesContainer';
 import PageAccessoriesContainer from '../services/PageAccessoriesContainer';
 
 
 const PageAccessories = (props) => {
 const PageAccessories = (props) => {
-  const { appContainer, pageAccessoriesContainer } = props;
+  const { appContainer, pageAccessoriesContainer, isNotFoundPage } = props;
   const { isGuestUser, isSharedUser } = appContainer;
   const { isGuestUser, isSharedUser } = appContainer;
 
 
   return (
   return (
@@ -17,10 +17,12 @@ const PageAccessories = (props) => {
       <PageAccessoriesModalControl
       <PageAccessoriesModalControl
         isGuestUser={isGuestUser}
         isGuestUser={isGuestUser}
         isSharedUser={isSharedUser}
         isSharedUser={isSharedUser}
+        isNotFoundPage={isNotFoundPage}
       />
       />
       <PageAccessoriesModal
       <PageAccessoriesModal
         isGuestUser={isGuestUser}
         isGuestUser={isGuestUser}
         isSharedUser={isSharedUser}
         isSharedUser={isSharedUser}
+        isNotFoundPage={isNotFoundPage}
         isOpen={pageAccessoriesContainer.state.isPageAccessoriesModalShown}
         isOpen={pageAccessoriesContainer.state.isPageAccessoriesModalShown}
         onClose={pageAccessoriesContainer.closePageAccessoriesModal}
         onClose={pageAccessoriesContainer.closePageAccessoriesModal}
       />
       />
@@ -35,6 +37,8 @@ const PageAccessoriesWrapper = withUnstatedContainers(PageAccessories, [AppConta
 PageAccessories.propTypes = {
 PageAccessories.propTypes = {
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   pageAccessoriesContainer: PropTypes.instanceOf(PageAccessoriesContainer).isRequired,
   pageAccessoriesContainer: PropTypes.instanceOf(PageAccessoriesContainer).isRequired,
+
+  isNotFoundPage: PropTypes.bool.isRequired,
 };
 };
 
 
 export default PageAccessoriesWrapper;
 export default PageAccessoriesWrapper;

+ 8 - 6
src/client/js/components/PageAccessoriesModal.jsx

@@ -24,7 +24,7 @@ import ExpandOrContractButton from './ExpandOrContractButton';
 
 
 const PageAccessoriesModal = (props) => {
 const PageAccessoriesModal = (props) => {
   const {
   const {
-    t, pageAccessoriesContainer, onClose, isGuestUser, isSharedUser,
+    t, pageAccessoriesContainer, onClose, isGuestUser, isSharedUser, isNotFoundPage,
   } = props;
   } = props;
   const { switchActiveTab } = pageAccessoriesContainer;
   const { switchActiveTab } = pageAccessoriesContainer;
   const { activeTab, activeComponents } = pageAccessoriesContainer.state;
   const { activeTab, activeComponents } = pageAccessoriesContainer.state;
@@ -48,21 +48,22 @@ const PageAccessoriesModal = (props) => {
         Icon: HistoryIcon,
         Icon: HistoryIcon,
         i18n: t('History'),
         i18n: t('History'),
         index: 2,
         index: 2,
-        isLinkEnabled: v => !isGuestUser && !isSharedUser,
+        isLinkEnabled: v => !isGuestUser && !isSharedUser && !isNotFoundPage,
       },
       },
       attachment: {
       attachment: {
         Icon: AttachmentIcon,
         Icon: AttachmentIcon,
         i18n: t('attachment_data'),
         i18n: t('attachment_data'),
         index: 3,
         index: 3,
+        isLinkEnabled: v => !isNotFoundPage,
       },
       },
       shareLink: {
       shareLink: {
         Icon: ShareLinkIcon,
         Icon: ShareLinkIcon,
         i18n: t('share_links.share_link_management'),
         i18n: t('share_links.share_link_management'),
         index: 4,
         index: 4,
-        isLinkEnabled: v => !isGuestUser && !isSharedUser,
+        isLinkEnabled: v => !isGuestUser && !isSharedUser && !isNotFoundPage,
       },
       },
     };
     };
-  }, [t, isGuestUser, isSharedUser]);
+  }, [t, isGuestUser, isSharedUser, isNotFoundPage]);
 
 
   const closeModalHandler = useCallback(() => {
   const closeModalHandler = useCallback(() => {
     if (onClose == null) {
     if (onClose == null) {
@@ -109,10 +110,10 @@ const PageAccessoriesModal = (props) => {
             hideBorderBottom
             hideBorderBottom
           />
           />
         </ModalHeader>
         </ModalHeader>
-        <ModalBody className="overflow-auto grw-modal-body-style p-0">
+        <ModalBody className="overflow-auto grw-modal-body-style">
           {/* Do not use CustomTabContent because of performance problem:
           {/* Do not use CustomTabContent because of performance problem:
               the 'navTabMapping[tabId].Content' for PageAccessoriesModal depends on activeComponents */}
               the 'navTabMapping[tabId].Content' for PageAccessoriesModal depends on activeComponents */}
-          <TabContent activeTab={activeTab} className="p-5">
+          <TabContent activeTab={activeTab}>
             <TabPane tabId="pagelist">
             <TabPane tabId="pagelist">
               {activeComponents.has('pagelist') && <PageList />}
               {activeComponents.has('pagelist') && <PageList />}
             </TabPane>
             </TabPane>
@@ -149,6 +150,7 @@ PageAccessoriesModal.propTypes = {
   pageAccessoriesContainer: PropTypes.instanceOf(PageAccessoriesContainer).isRequired,
   pageAccessoriesContainer: PropTypes.instanceOf(PageAccessoriesContainer).isRequired,
   isGuestUser: PropTypes.bool.isRequired,
   isGuestUser: PropTypes.bool.isRequired,
   isSharedUser: PropTypes.bool.isRequired,
   isSharedUser: PropTypes.bool.isRequired,
+  isNotFoundPage: PropTypes.bool.isRequired,
   isOpen: PropTypes.bool.isRequired,
   isOpen: PropTypes.bool.isRequired,
   onClose: PropTypes.func,
   onClose: PropTypes.func,
 };
 };

+ 16 - 6
src/client/js/components/PageAccessoriesModalControl.jsx

@@ -17,7 +17,7 @@ import { withUnstatedContainers } from './UnstatedUtils';
 
 
 const PageAccessoriesModalControl = (props) => {
 const PageAccessoriesModalControl = (props) => {
   const {
   const {
-    t, pageAccessoriesContainer, isGuestUser, isSharedUser,
+    t, pageAccessoriesContainer, isGuestUser, isSharedUser, isNotFoundPage,
   } = props;
   } = props;
 
 
   const accessoriesBtnList = useMemo(() => {
   const accessoriesBtnList = useMemo(() => {
@@ -37,27 +37,36 @@ const PageAccessoriesModalControl = (props) => {
       {
       {
         name: 'pageHistory',
         name: 'pageHistory',
         Icon: <HistoryIcon />,
         Icon: <HistoryIcon />,
-        disabled: isGuestUser || isSharedUser,
+        disabled: isGuestUser || isSharedUser || isNotFoundPage,
         i18n: t('History'),
         i18n: t('History'),
       },
       },
       {
       {
         name: 'attachment',
         name: 'attachment',
         Icon: <AttachmentIcon />,
         Icon: <AttachmentIcon />,
-        disabled: false,
+        disabled: isNotFoundPage,
         i18n: t('attachment_data'),
         i18n: t('attachment_data'),
       },
       },
       {
       {
         name: 'shareLink',
         name: 'shareLink',
         Icon: <ShareLinkIcon />,
         Icon: <ShareLinkIcon />,
-        disabled: isGuestUser || isSharedUser,
+        disabled: isGuestUser || isSharedUser || isNotFoundPage,
         i18n: t('share_links.share_link_management'),
         i18n: t('share_links.share_link_management'),
       },
       },
     ];
     ];
-  }, [t, isGuestUser, isSharedUser]);
+  }, [t, isGuestUser, isSharedUser, isNotFoundPage]);
 
 
   return (
   return (
     <div className="grw-page-accessories-control d-flex flex-nowrap align-items-center justify-content-end justify-content-lg-between">
     <div className="grw-page-accessories-control d-flex flex-nowrap align-items-center justify-content-end justify-content-lg-between">
       {accessoriesBtnList.map((accessory) => {
       {accessoriesBtnList.map((accessory) => {
+
+        let tooltipMessage;
+        if (accessory.disabled) {
+          tooltipMessage = isNotFoundPage ? t('not_found_page.page_not_exist') : t('Not available for guest');
+        }
+        else {
+          tooltipMessage = accessory.i18n;
+        }
+
         return (
         return (
           <Fragment key={accessory.name}>
           <Fragment key={accessory.name}>
             <div id={`shareLink-btn-wrapper-for-tooltip-for-${accessory.name}`}>
             <div id={`shareLink-btn-wrapper-for-tooltip-for-${accessory.name}`}>
@@ -70,7 +79,7 @@ const PageAccessoriesModalControl = (props) => {
               </button>
               </button>
             </div>
             </div>
             <UncontrolledTooltip placement="top" target={`shareLink-btn-wrapper-for-tooltip-for-${accessory.name}`} fade={false}>
             <UncontrolledTooltip placement="top" target={`shareLink-btn-wrapper-for-tooltip-for-${accessory.name}`} fade={false}>
-              {accessory.disabled ? t('Not available for guest') : accessory.i18n}
+              {tooltipMessage}
             </UncontrolledTooltip>
             </UncontrolledTooltip>
           </Fragment>
           </Fragment>
         );
         );
@@ -94,6 +103,7 @@ PageAccessoriesModalControl.propTypes = {
 
 
   isGuestUser: PropTypes.bool.isRequired,
   isGuestUser: PropTypes.bool.isRequired,
   isSharedUser: PropTypes.bool.isRequired,
   isSharedUser: PropTypes.bool.isRequired,
+  isNotFoundPage: PropTypes.bool.isRequired,
 };
 };
 
 
 export default withTranslation()(PageAccessoriesModalControlWrapper);
 export default withTranslation()(PageAccessoriesModalControlWrapper);

+ 20 - 10
src/client/js/components/PageHistory.jsx

@@ -2,21 +2,23 @@ import React, { useCallback } from 'react';
 import PropTypes from 'prop-types';
 import PropTypes from 'prop-types';
 import loggerFactory from '@alias/logger';
 import loggerFactory from '@alias/logger';
 
 
+import { withTranslation } from 'react-i18next';
 import { withUnstatedContainers } from './UnstatedUtils';
 import { withUnstatedContainers } from './UnstatedUtils';
 import { toastError } from '../util/apiNotification';
 import { toastError } from '../util/apiNotification';
 
 
 import { withLoadingSppiner } from './SuspenseUtils';
 import { withLoadingSppiner } from './SuspenseUtils';
-import PageRevisionList from './PageHistory/PageRevisionList';
+import PageRevisionTable from './PageHistory/PageRevisionTable';
 
 
 import PageHistroyContainer from '../services/PageHistoryContainer';
 import PageHistroyContainer from '../services/PageHistoryContainer';
 import PaginationWrapper from './PaginationWrapper';
 import PaginationWrapper from './PaginationWrapper';
-
+import RevisionComparer from './RevisionComparer/RevisionComparer';
+import RevisionComparerContainer from '../services/RevisionComparerContainer';
 
 
 const logger = loggerFactory('growi:PageHistory');
 const logger = loggerFactory('growi:PageHistory');
 
 
 function PageHistory(props) {
 function PageHistory(props) {
-  const { pageHistoryContainer } = props;
-  const { getPreviousRevision, onDiffOpenClicked } = pageHistoryContainer;
+  const { pageHistoryContainer, revisionComparerContainer, t } = props;
+  const { getPreviousRevision } = pageHistoryContainer;
   const {
   const {
     activePage, totalPages, pagingLimit, revisions, diffOpened,
     activePage, totalPages, pagingLimit, revisions, diffOpened,
   } = pageHistoryContainer.state;
   } = pageHistoryContainer.state;
@@ -44,6 +46,7 @@ function PageHistory(props) {
     throw new Promise(async() => {
     throw new Promise(async() => {
       try {
       try {
         await props.pageHistoryContainer.retrieveRevisions(1);
         await props.pageHistoryContainer.retrieveRevisions(1);
+        await props.revisionComparerContainer.initRevisions();
       }
       }
       catch (err) {
       catch (err) {
         toastError(err);
         toastError(err);
@@ -66,24 +69,31 @@ function PageHistory(props) {
   }
   }
 
 
   return (
   return (
-    <div>
-      <PageRevisionList
+    <div className="revision-history">
+      <h3 className="pb-3">{t('page_history.revision_list')}</h3>
+      <PageRevisionTable
         pageHistoryContainer={pageHistoryContainer}
         pageHistoryContainer={pageHistoryContainer}
+        revisionComparerContainer={revisionComparerContainer}
         revisions={revisions}
         revisions={revisions}
         diffOpened={diffOpened}
         diffOpened={diffOpened}
         getPreviousRevision={getPreviousRevision}
         getPreviousRevision={getPreviousRevision}
-        onDiffOpenClicked={onDiffOpenClicked}
       />
       />
-      {pager()}
+      <div className="my-3">
+        {pager()}
+      </div>
+      <RevisionComparer />
     </div>
     </div>
   );
   );
 
 
 }
 }
 
 
-const RenderPageHistoryWrapper = withUnstatedContainers(withLoadingSppiner(PageHistory), [PageHistroyContainer]);
+const RenderPageHistoryWrapper = withUnstatedContainers(withLoadingSppiner(PageHistory), [PageHistroyContainer, RevisionComparerContainer]);
 
 
 PageHistory.propTypes = {
 PageHistory.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+
   pageHistoryContainer: PropTypes.instanceOf(PageHistroyContainer).isRequired,
   pageHistoryContainer: PropTypes.instanceOf(PageHistroyContainer).isRequired,
+  revisionComparerContainer: PropTypes.instanceOf(RevisionComparerContainer).isRequired,
 };
 };
 
 
-export default RenderPageHistoryWrapper;
+export default withTranslation()(RenderPageHistoryWrapper);

+ 0 - 133
src/client/js/components/PageHistory/PageRevisionList.jsx

@@ -1,133 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-
-import { withTranslation } from 'react-i18next';
-import PageHistroyContainer from '../../services/PageHistoryContainer';
-
-import Revision from './Revision';
-import RevisionDiff from './RevisionDiff';
-
-class PageRevisionList extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      isCompactNodiffRevisions: true,
-    };
-
-    this.cbCompactizeChangeHandler = this.cbCompactizeChangeHandler.bind(this);
-  }
-
-  cbCompactizeChangeHandler() {
-    this.setState({ isCompactNodiffRevisions: !this.state.isCompactNodiffRevisions });
-  }
-
-  /**
-   * render a row (Revision component and RevisionDiff component)
-   * @param {Revison} revision
-   * @param {Revision} previousRevision
-   * @param {boolean} hasDiff whether revision has difference to previousRevision
-   * @param {boolean} isContiguousNodiff true if the current 'hasDiff' and one of previous row is both false
-   */
-  renderRow(revision, previousRevision, hasDiff, isContiguousNodiff) {
-    const revisionId = revision._id;
-    const revisionDiffOpened = this.props.diffOpened[revisionId] || false;
-
-    const classNames = ['revision-history-outer'];
-    if (isContiguousNodiff) {
-      classNames.push('revision-history-outer-contiguous-nodiff');
-    }
-
-    return (
-      <div className={classNames.join(' ')} key={`revision-history-${revisionId}`}>
-        <Revision
-          t={this.props.t}
-          revision={revision}
-          revisionDiffOpened={revisionDiffOpened}
-          hasDiff={hasDiff}
-          isCompactNodiffRevisions={this.state.isCompactNodiffRevisions}
-          onDiffOpenClicked={this.props.onDiffOpenClicked}
-          key={`revision-history-rev-${revisionId}`}
-        />
-        { hasDiff
-          && (
-          <RevisionDiff
-            revisionDiffOpened={revisionDiffOpened}
-            currentRevision={revision}
-            previousRevision={previousRevision}
-            key={`revision-deff-${revisionId}`}
-          />
-          )
-        }
-      </div>
-    );
-  }
-
-  render() {
-    const { t, pageHistoryContainer } = this.props;
-
-    const revisions = this.props.revisions;
-    const revisionCount = this.props.revisions.length;
-
-    let hasDiffPrev;
-
-    const revisionList = this.props.revisions.map((revision, idx) => {
-      // Returns null because the last revision is for the bottom diff display
-      if (idx === pageHistoryContainer.state.pagingLimit) {
-        return null;
-      }
-
-      let previousRevision;
-      if (idx + 1 < revisionCount) {
-        previousRevision = revisions[idx + 1];
-      }
-      else {
-        previousRevision = revision; // if it is the first revision, show full text as diff text
-      }
-
-      const hasDiff = revision.hasDiffToPrev !== false; // set 'true' if undefined for backward compatibility
-      const isContiguousNodiff = !hasDiff && !hasDiffPrev;
-
-      hasDiffPrev = hasDiff;
-
-      return this.renderRow(revision, previousRevision, hasDiff, isContiguousNodiff);
-    });
-
-    const classNames = ['revision-history-list'];
-    if (this.state.isCompactNodiffRevisions) {
-      classNames.push('revision-history-list-compact');
-    }
-
-    return (
-      <React.Fragment>
-        <div className="custom-control custom-checkbox custom-checkbox-info float-right">
-          <input
-            type="checkbox"
-            id="cbCompactize"
-            className="custom-control-input"
-            checked={this.state.isCompactNodiffRevisions}
-            onChange={this.cbCompactizeChangeHandler}
-          />
-          <label className="custom-control-label" htmlFor="cbCompactize">{ t('Shrink versions that have no diffs') }</label>
-        </div>
-        <div className="clearfix"></div>
-        <div className={classNames.join(' ')}>
-          {revisionList}
-        </div>
-      </React.Fragment>
-    );
-  }
-
-}
-
-PageRevisionList.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  pageHistoryContainer: PropTypes.instanceOf(PageHistroyContainer).isRequired,
-
-  revisions: PropTypes.array,
-  diffOpened: PropTypes.object,
-  onDiffOpenClicked: PropTypes.func.isRequired,
-};
-
-export default withTranslation()(PageRevisionList);

+ 165 - 0
src/client/js/components/PageHistory/PageRevisionTable.jsx

@@ -0,0 +1,165 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import { withTranslation } from 'react-i18next';
+import PageHistroyContainer from '../../services/PageHistoryContainer';
+import RevisionComparerContainer from '../../services/RevisionComparerContainer';
+
+import Revision from './Revision';
+
+class PageRevisionTable extends React.Component {
+
+  /**
+   * render a row (Revision component and RevisionDiff component)
+   * @param {Revison} revision
+   * @param {Revision} previousRevision
+   * @param {boolean} hasDiff whether revision has difference to previousRevision
+   * @param {boolean} isContiguousNodiff true if the current 'hasDiff' and one of previous row is both false
+   */
+  renderRow(revision, previousRevision, hasDiff, isContiguousNodiff) {
+    const { revisionComparerContainer, t } = this.props;
+    const { latestRevision, oldestRevision } = this.props.pageHistoryContainer.state;
+    const revisionId = revision._id;
+    const revisionDiffOpened = this.props.diffOpened[revisionId] || false;
+    const { sourceRevision, targetRevision } = revisionComparerContainer.state;
+
+    const handleCompareLatestRevisionButton = () => {
+      revisionComparerContainer.setState({ sourceRevision: revision });
+      revisionComparerContainer.setState({ targetRevision: latestRevision });
+    };
+
+    const handleComparePreviousRevisionButton = () => {
+      revisionComparerContainer.setState({ sourceRevision: previousRevision });
+      revisionComparerContainer.setState({ targetRevision: revision });
+    };
+
+    return (
+      <tr className="d-flex" key={`revision-history-${revisionId}`}>
+        <td className="col" key={`revision-history-top-${revisionId}`}>
+          <div className="d-lg-flex">
+            <Revision
+              t={this.props.t}
+              revision={revision}
+              isLatestRevision={revision === latestRevision}
+              revisionDiffOpened={revisionDiffOpened}
+              hasDiff={hasDiff}
+              key={`revision-history-rev-${revisionId}`}
+            />
+            {hasDiff && (
+              <div className="ml-md-3 mt-auto">
+                <div className="btn-group">
+                  <button
+                    type="button"
+                    className="btn btn-outline-secondary btn-sm"
+                    onClick={handleCompareLatestRevisionButton}
+                  >
+                    {t('page_history.compare_latest')}
+                  </button>
+                  <button
+                    type="button"
+                    className="btn btn-outline-secondary btn-sm"
+                    onClick={handleComparePreviousRevisionButton}
+                    disabled={revision === oldestRevision}
+                  >
+                    {t('page_history.compare_previous')}
+                  </button>
+                </div>
+              </div>
+           )}
+          </div>
+        </td>
+        <td className="col-1">
+          {(hasDiff || revision._id === sourceRevision?._id) && (
+            <div className="custom-control custom-radio custom-control-inline mr-0">
+              <input
+                type="radio"
+                className="custom-control-input"
+                id={`compareSource-${revision._id}`}
+                name="compareSource"
+                value={revision._id}
+                checked={revision._id === sourceRevision?._id}
+                onChange={() => revisionComparerContainer.setState({ sourceRevision: revision })}
+              />
+              <label className="custom-control-label" htmlFor={`compareSource-${revision._id}`} />
+            </div>
+          )}
+        </td>
+        <td className="col-2">
+          {(hasDiff || revision._id === targetRevision?._id) && (
+            <div className="custom-control custom-radio custom-control-inline mr-0">
+              <input
+                type="radio"
+                className="custom-control-input"
+                id={`compareTarget-${revision._id}`}
+                name="compareTarget"
+                value={revision._id}
+                checked={revision._id === targetRevision?._id}
+                onChange={() => revisionComparerContainer.setState({ targetRevision: revision })}
+              />
+              <label className="custom-control-label" htmlFor={`compareTarget-${revision._id}`} />
+            </div>
+          )}
+        </td>
+      </tr>
+    );
+  }
+
+  render() {
+    const { t, pageHistoryContainer } = this.props;
+
+    const revisions = this.props.revisions;
+    const revisionCount = this.props.revisions.length;
+
+    let hasDiffPrev;
+
+    const revisionList = this.props.revisions.map((revision, idx) => {
+      // Returns null because the last revision is for the bottom diff display
+      if (idx === pageHistoryContainer.state.pagingLimit) {
+        return null;
+      }
+
+      let previousRevision;
+      if (idx + 1 < revisionCount) {
+        previousRevision = revisions[idx + 1];
+      }
+      else {
+        previousRevision = revision; // if it is the first revision, show full text as diff text
+      }
+
+
+      const hasDiff = revision.hasDiffToPrev !== false; // set 'true' if undefined for backward compatibility
+      const isContiguousNodiff = !hasDiff && !hasDiffPrev;
+
+      hasDiffPrev = hasDiff;
+
+      return this.renderRow(revision, previousRevision, hasDiff, isContiguousNodiff);
+    });
+
+    return (
+      <table className="table revision-history-table">
+        <thead>
+          <tr className="d-flex">
+            <th className="col">{ t('page_history.revision') }</th>
+            <th className="col-1">{ t('page_history.comparing_source') }</th>
+            <th className="col-2">{ t('page_history.comparing_target') }</th>
+          </tr>
+        </thead>
+        <tbody className="overflow-auto d-block">
+          {revisionList}
+        </tbody>
+      </table>
+    );
+  }
+
+}
+
+PageRevisionTable.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  pageHistoryContainer: PropTypes.instanceOf(PageHistroyContainer).isRequired,
+  revisionComparerContainer: PropTypes.instanceOf(RevisionComparerContainer).isRequired,
+
+  revisions: PropTypes.array,
+  diffOpened: PropTypes.object,
+};
+
+export default withTranslation()(PageRevisionTable);

+ 15 - 45
src/client/js/components/PageHistory/Revision.jsx

@@ -7,20 +7,9 @@ import UserPicture from '../User/UserPicture';
 
 
 export default class Revision extends React.Component {
 export default class Revision extends React.Component {
 
 
-  constructor(props) {
-    super(props);
-
-    this._onDiffOpenClicked = this._onDiffOpenClicked.bind(this);
-  }
-
   componentDidMount() {
   componentDidMount() {
   }
   }
 
 
-  _onDiffOpenClicked(e) {
-    e.preventDefault();
-    this.props.onDiffOpenClicked(this.props.revision);
-  }
-
   renderSimplifiedNodiff(revision) {
   renderSimplifiedNodiff(revision) {
     const { t } = this.props;
     const { t } = this.props;
 
 
@@ -37,11 +26,9 @@ export default class Revision extends React.Component {
           {pic}
           {pic}
         </div>
         </div>
         <div className="ml-3">
         <div className="ml-3">
-          <div className="revision-history-meta">
-            <span className="text-muted small">
-              <UserDate dateTime={revision.createdAt} /> ({ t('No diff') })
-            </span>
-          </div>
+          <span className="text-muted small">
+            <UserDate dateTime={revision.createdAt} /> ({ t('No diff') })
+          </span>
         </div>
         </div>
       </div>
       </div>
     );
     );
@@ -57,38 +44,22 @@ export default class Revision extends React.Component {
       pic = <UserPicture user={author} size="lg" />;
       pic = <UserPicture user={author} size="lg" />;
     }
     }
 
 
-    const iconClass = this.props.revisionDiffOpened ? 'fa fa-caret-down caret caret-opened' : 'fa fa-caret-down caret';
     return (
     return (
-      <div className="revision-history-main d-flex mt-3">
-        <div className="mt-2">
+      <div className="revision-history-main d-flex">
+        <div className="picture-container">
           {pic}
           {pic}
         </div>
         </div>
         <div className="ml-2">
         <div className="ml-2">
-          <div className="revision-history-author">
+          <div className="revision-history-author mb-1">
             <strong><Username user={author}></Username></strong>
             <strong><Username user={author}></Username></strong>
+            {this.props.isLatestRevision && <span className="badge badge-info ml-2">Latest</span>}
           </div>
           </div>
-          <div className="revision-history-meta">
-            <p>
-              <UserDate dateTime={revision.createdAt} />
-            </p>
-            <p>
-              <span className="d-inline-block" style={{ minWidth: '90px' }}>
-                { !this.props.hasDiff
-                  && <span className="text-muted">{ t('No diff') }</span>
-                }
-                { this.props.hasDiff
-                  && (
-                  // use dummy href attr (with preventDefault()), because don't apply style by a:not([href])
-                  <a className="diff-view" href="" onClick={this._onDiffOpenClicked}>
-                    <i className={iconClass}></i> {t('View diff')}
-                  </a>
-                  )
-                }
-              </span>
-              <a href={`?revision=${revision._id}`} className="ml-2">
-                <i className="icon-login"></i> { t('Go to this version') }
-              </a>
-            </p>
+          <div className="mb-1">
+            <UserDate dateTime={revision.createdAt} />
+            <br className="d-xl-none d-block" />
+            <a className="ml-xl-3" href={`?revision=${revision._id}`}>
+              <i className="icon-login"></i> { t('Go to this version') }
+            </a>
           </div>
           </div>
         </div>
         </div>
       </div>
       </div>
@@ -98,7 +69,7 @@ export default class Revision extends React.Component {
   render() {
   render() {
     const revision = this.props.revision;
     const revision = this.props.revision;
 
 
-    if (this.props.isCompactNodiffRevisions && !this.props.hasDiff) {
+    if (!this.props.hasDiff) {
       return this.renderSimplifiedNodiff(revision);
       return this.renderSimplifiedNodiff(revision);
     }
     }
 
 
@@ -111,8 +82,7 @@ export default class Revision extends React.Component {
 Revision.propTypes = {
 Revision.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   t: PropTypes.func.isRequired, // i18next
   revision: PropTypes.object,
   revision: PropTypes.object,
+  isLatestRevision: PropTypes.bool.isRequired,
   revisionDiffOpened: PropTypes.bool.isRequired,
   revisionDiffOpened: PropTypes.bool.isRequired,
   hasDiff: PropTypes.bool.isRequired,
   hasDiff: PropTypes.bool.isRequired,
-  isCompactNodiffRevisions: PropTypes.bool.isRequired,
-  onDiffOpenClicked: PropTypes.func.isRequired,
 };
 };

+ 32 - 3
src/client/js/components/PageHistory/RevisionDiff.jsx

@@ -1,12 +1,16 @@
+/* eslint-disable react/no-danger */
 import React from 'react';
 import React from 'react';
 import PropTypes from 'prop-types';
 import PropTypes from 'prop-types';
 
 
 import { createPatch } from 'diff';
 import { createPatch } from 'diff';
 import { html } from 'diff2html';
 import { html } from 'diff2html';
+import { withTranslation } from 'react-i18next';
+import UserDate from '../User/UserDate';
 
 
-export default class RevisionDiff extends React.Component {
+class RevisionDiff extends React.Component {
 
 
   render() {
   render() {
+    const { t } = this.props;
     const currentRevision = this.props.currentRevision;
     const currentRevision = this.props.currentRevision;
     const previousRevision = this.props.previousRevision;
     const previousRevision = this.props.previousRevision;
     const revisionDiffOpened = this.props.revisionDiffOpened;
     const revisionDiffOpened = this.props.revisionDiffOpened;
@@ -38,14 +42,39 @@ export default class RevisionDiff extends React.Component {
     }
     }
 
 
     const diffView = { __html: diffViewHTML };
     const diffView = { __html: diffViewHTML };
-    // eslint-disable-next-line react/no-danger
-    return <div className="revision-history-diff" dangerouslySetInnerHTML={diffView} />;
+    return (
+      <>
+        <div className="comparison-header">
+          <div className="container pt-1 pr-0">
+            <div className="row">
+              <div className="col comparison-source-wrapper pt-1 px-0">
+                <span className="comparison-source pr-3">{t('page_history.comparing_source')}</span><UserDate dateTime={previousRevision.createdAt} />
+                <a href={`?revision=${previousRevision._id}`} className="ml-3">
+                  <i className="icon-login"></i>
+                </a>
+
+              </div>
+              <div className="col comparison-target-wrapper pt-1">
+                <span className="comparison-target pr-3">{t('page_history.comparing_target')}</span><UserDate dateTime={currentRevision.createdAt} />
+                <a href={`?revision=${currentRevision._id}`} className="ml-3">
+                  <i className="icon-login"></i>
+                </a>
+              </div>
+            </div>
+          </div>
+        </div>
+        <div className="revision-history-diff" dangerouslySetInnerHTML={diffView} />
+      </>
+    );
   }
   }
 
 
 }
 }
 
 
 RevisionDiff.propTypes = {
 RevisionDiff.propTypes = {
+  t: PropTypes.func.isRequired,
   currentRevision: PropTypes.object.isRequired,
   currentRevision: PropTypes.object.isRequired,
   previousRevision: PropTypes.object.isRequired,
   previousRevision: PropTypes.object.isRequired,
   revisionDiffOpened: PropTypes.bool.isRequired,
   revisionDiffOpened: PropTypes.bool.isRequired,
 };
 };
+
+export default withTranslation()(RevisionDiff);

+ 116 - 0
src/client/js/components/RevisionComparer/RevisionComparer.jsx

@@ -0,0 +1,116 @@
+import React, { useState } from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+import { CopyToClipboard } from 'react-copy-to-clipboard';
+import {
+  Dropdown, DropdownToggle, DropdownMenu, DropdownItem,
+} from 'reactstrap';
+
+import { withUnstatedContainers } from '../UnstatedUtils';
+
+import RevisionComparerContainer from '../../services/RevisionComparerContainer';
+
+import RevisionDiff from '../PageHistory/RevisionDiff';
+
+/* eslint-disable react/prop-types */
+const DropdownItemContents = ({ title, contents }) => (
+  <>
+    <div className="h6 mt-1 mb-2"><strong>{title}</strong></div>
+    <div className="card well mb-1 p-2">{contents}</div>
+  </>
+);
+/* eslint-enable react/prop-types */
+
+function encodeSpaces(str) {
+  if (str == null) {
+    return null;
+  }
+
+  // Encode SPACE and IDEOGRAPHIC SPACE
+  return str.replace(/ /g, '%20').replace(/\u3000/g, '%E3%80%80');
+}
+
+const RevisionComparer = (props) => {
+
+  const [dropdownOpen, setDropdownOpen] = useState(false);
+
+  const { t, revisionComparerContainer } = props;
+
+  function toggleDropdown() {
+    setDropdownOpen(!dropdownOpen);
+  }
+
+  const pagePathUrl = () => {
+    const { origin } = window.location;
+    const { path } = revisionComparerContainer.pageContainer.state;
+    const { sourceRevision, targetRevision } = revisionComparerContainer.state;
+
+    const url = new URL(path, origin);
+
+    if (sourceRevision != null && targetRevision != null) {
+      const urlParams = `${sourceRevision._id}...${targetRevision._id}`;
+      url.searchParams.set('compare', urlParams);
+    }
+
+    return encodeSpaces(decodeURI(url));
+  };
+
+  const { sourceRevision, targetRevision } = revisionComparerContainer.state;
+
+  if (sourceRevision == null || targetRevision == null) {
+    return null;
+  }
+
+  return (
+    <div className="revision-compare">
+      <div className="d-flex">
+        <h4 className="align-self-center">{ t('page_history.comparing_revisions') }</h4>
+        <Dropdown
+          className="grw-copy-dropdown align-self-center ml-auto"
+          isOpen={dropdownOpen}
+          toggle={() => toggleDropdown()}
+        >
+          <DropdownToggle
+            caret
+            className="d-block text-muted bg-transparent btn-copy border-0 py-0"
+          >
+            <i className="ti-clipboard"></i>
+          </DropdownToggle>
+          <DropdownMenu positionFixed modifiers={{ preventOverflow: { boundariesElement: null } }}>
+            {/* Page path URL */}
+            <CopyToClipboard text={pagePathUrl()}>
+              <DropdownItem className="px-3">
+                <DropdownItemContents title={t('copy_to_clipboard.Page URL')} contents={pagePathUrl()} />
+              </DropdownItem>
+            </CopyToClipboard>
+            <DropdownItem divider className="my-0"></DropdownItem>
+          </DropdownMenu>
+        </Dropdown>
+      </div>
+
+      <div className="revision-compare-outer">
+        {sourceRevision._id === targetRevision._id ? t('No diff') : (
+          <RevisionDiff
+            revisionDiffOpened
+            previousRevision={sourceRevision}
+            currentRevision={targetRevision}
+          />
+        )}
+      </div>
+    </div>
+  );
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const RevisionComparerWrapper = withUnstatedContainers(RevisionComparer, [RevisionComparerContainer]);
+
+RevisionComparer.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  revisionComparerContainer: PropTypes.instanceOf(RevisionComparerContainer).isRequired,
+
+  revisions: PropTypes.array,
+};
+
+export default withTranslation()(RevisionComparerWrapper);

+ 3 - 0
src/client/js/services/EditorContainer.js

@@ -151,7 +151,10 @@ export default class EditorContainer extends Container {
     return opt;
     return opt;
   }
   }
 
 
+  // See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#example
   showUnsavedWarning(e) {
   showUnsavedWarning(e) {
+    // Cancel the event
+    e.preventDefault();
     // display browser default message
     // display browser default message
     e.returnValue = '';
     e.returnValue = '';
     return '';
     return '';

+ 10 - 12
src/client/js/services/PageHistoryContainer.js

@@ -24,6 +24,8 @@ export default class PageHistoryContainer extends Container {
 
 
       // set dummy rivisions for using suspense
       // set dummy rivisions for using suspense
       revisions: this.dummyRevisions,
       revisions: this.dummyRevisions,
+      latestRevision: this.dummyRevisions,
+      oldestRevision: this.dummyRevisions,
       diffOpened: {},
       diffOpened: {},
 
 
       totalPages: 0,
       totalPages: 0,
@@ -32,7 +34,6 @@ export default class PageHistoryContainer extends Container {
     };
     };
 
 
     this.retrieveRevisions = this.retrieveRevisions.bind(this);
     this.retrieveRevisions = this.retrieveRevisions.bind(this);
-    this.onDiffOpenClicked = this.onDiffOpenClicked.bind(this);
     this.getPreviousRevision = this.getPreviousRevision.bind(this);
     this.getPreviousRevision = this.getPreviousRevision.bind(this);
     this.fetchPageRevisionBody = this.fetchPageRevisionBody.bind(this);
     this.fetchPageRevisionBody = this.fetchPageRevisionBody.bind(this);
   }
   }
@@ -96,6 +97,14 @@ export default class PageHistoryContainer extends Container {
     this.setState({ revisions: rev });
     this.setState({ revisions: rev });
     this.setState({ diffOpened });
     this.setState({ diffOpened });
 
 
+    if (selectedPage === 1) {
+      this.setState({ latestRevision: rev[0] });
+    }
+
+    if (selectedPage === res.data.totalPages) {
+      this.setState({ oldestRevision: rev[lastId] });
+    }
+
     // load 0, and last default
     // load 0, and last default
     if (rev[0]) {
     if (rev[0]) {
       this.fetchPageRevisionBody(rev[0]);
       this.fetchPageRevisionBody(rev[0]);
@@ -110,17 +119,6 @@ export default class PageHistoryContainer extends Container {
     return;
     return;
   }
   }
 
 
-  onDiffOpenClicked(revision) {
-    const { diffOpened } = this.state;
-    const revisionId = revision._id;
-
-    diffOpened[revisionId] = !(diffOpened[revisionId]);
-    this.setState(diffOpened);
-
-    this.fetchPageRevisionBody(revision);
-    this.fetchPageRevisionBody(this.getPreviousRevision(revision));
-  }
-
   getPreviousRevision(currentRevision) {
   getPreviousRevision(currentRevision) {
     let cursor = null;
     let cursor = null;
     for (const revision of this.state.revisions) {
     for (const revision of this.state.revisions) {

+ 112 - 0
src/client/js/services/RevisionComparerContainer.js

@@ -0,0 +1,112 @@
+import { Container } from 'unstated';
+
+import loggerFactory from '@alias/logger';
+
+import { toastError } from '../util/apiNotification';
+
+const logger = loggerFactory('growi:PageHistoryContainer');
+
+/**
+ * Service container for personal settings page (RevisionCompare.jsx)
+ * @extends {Container} unstated Container
+ */
+export default class RevisionComparerContainer extends Container {
+
+  constructor(appContainer, pageContainer) {
+    super();
+
+    this.appContainer = appContainer;
+    this.pageContainer = pageContainer;
+
+    this.state = {
+      errMessage: null,
+
+      sourceRevision: null,
+      targetRevision: null,
+      latestRevision: null,
+    };
+
+    this.initRevisions = this.initRevisions.bind(this);
+  }
+
+  /**
+   * Workaround for the mangling in production build to break constructor.name
+   */
+  static getClassName() {
+    return 'RevisionComparerContainer';
+  }
+
+  /**
+   * Initialize the revisions
+   */
+  async initRevisions() {
+    const latestRevision = await this.fetchLatestRevision();
+
+    const [sourceRevisionId, targetRevisionId] = this.getRevisionIDsToCompareAsParam();
+    const sourceRevision = sourceRevisionId ? await this.fetchRevision(sourceRevisionId) : latestRevision;
+    const targetRevision = targetRevisionId ? await this.fetchRevision(targetRevisionId) : latestRevision;
+    const compareWithLatest = targetRevisionId ? false : this.state.compareWithLatest;
+
+    this.setState({
+      sourceRevision, targetRevision, latestRevision, compareWithLatest,
+    });
+  }
+
+  /**
+   * Get the IDs of the comparison source and target from "window.location" as an array
+   */
+  getRevisionIDsToCompareAsParam() {
+    const searchParams = {};
+    for (const param of window.location.search?.substr(1)?.split('&')) {
+      const [k, v] = param.split('=');
+      searchParams[k] = v;
+    }
+    if (!searchParams.compare) {
+      return [];
+    }
+
+    return searchParams.compare.split('...') || [];
+  }
+
+  /**
+   * Fetch the latest revision
+   */
+  async fetchLatestRevision() {
+    const { pageId, shareLinkId } = this.pageContainer.state;
+
+    try {
+      const res = await this.appContainer.apiv3Get('/revisions/list', {
+        pageId, shareLinkId, page: 1, limit: 1,
+      });
+      return res.data.docs[0];
+    }
+    catch (err) {
+      toastError(err);
+      this.setState({ errorMessage: err.message });
+      logger.error(err);
+    }
+    return null;
+  }
+
+  /**
+   * Fetch the revision of the specified ID
+   * @param {string} revision ID
+   */
+  async fetchRevision(revisionId) {
+    const { pageId, shareLinkId } = this.pageContainer.state;
+
+    try {
+      const res = await this.appContainer.apiv3Get(`/revisions/${revisionId}`, {
+        pageId, shareLinkId,
+      });
+      return res.data.revision;
+    }
+    catch (err) {
+      toastError(err);
+      this.setState({ errorMessage: err.message });
+      logger.error(err);
+    }
+    return null;
+  }
+
+}

+ 4 - 0
src/client/styles/scss/_page-accessories-modal.scss

@@ -5,6 +5,10 @@
     }
     }
   }
   }
 
 
+  .modal-body {
+    padding: 25px 30px;
+  }
+
   .grw-modal-body-style {
   .grw-modal-body-style {
     max-height: calc(100vh - 100px);
     max-height: calc(100vh - 100px);
   }
   }

+ 58 - 0
src/client/styles/scss/_page-history.scss

@@ -0,0 +1,58 @@
+// @import '../scss/variables';
+// @import '../scss/override-bootstrap-variables';
+
+.revision-history-table {
+  tbody {
+    max-height: 250px;
+  }
+}
+
+.revision-history-main {
+  img.picture-lg {
+    width: 32px;
+    height: 32px;
+  }
+}
+
+.revision-history-main-nodiff {
+  .picture-container {
+    min-width: 32px;
+    text-align: center; // centering .picture
+  }
+}
+
+.revision-history-diff {
+  color: $gray-900;
+  table-layout: fixed;
+}
+
+.comparison-header {
+  height: 34px;
+  background-color: #ffffff;
+  border: 1px solid $gray-300;
+  .comparison-source-wrapper {
+    height: 26px;
+    margin-right: 1px;
+    border-right: 1px solid $gray-300;
+    .comparison-source {
+      color: $gray-500;
+    }
+  }
+  .comparison-target-wrapper {
+    height: 26px;
+    .comparison-target {
+      color: $gray-500;
+    }
+  }
+}
+
+.revision-compare {
+  .revision-compare-outer {
+    min-height: 100px;
+    max-height: 250px;
+    overflow: auto;
+  }
+  .d2h-file-header {
+    display: none;
+  }
+}

+ 0 - 68
src/client/styles/scss/_page.scss

@@ -1,74 +1,6 @@
 // import diff2html styles
 // import diff2html styles
 @import '~diff2html/bundles/css/diff2html.min.css';
 @import '~diff2html/bundles/css/diff2html.min.css';
 
 
-.revision-history {
-  .revision-history-list {
-    .revision-history-outer {
-      // add border-top except of first element
-      &:not(:first-of-type) {
-        @extend .border-top;
-      }
-
-      .revision-history-main {
-        .picture-lg {
-          width: 32px;
-          height: 32px;
-        }
-
-        .revision-history-meta {
-          a:hover {
-            cursor: pointer;
-          }
-        }
-
-        .caret {
-          transition: 0.4s;
-          transform: rotate(-90deg);
-
-          &.caret-opened {
-            transform: rotate(0deg);
-          }
-        }
-      }
-
-      .revision-history-main-nodiff {
-        .picture-container {
-          min-width: 32px;
-          text-align: center; // centering .picture
-        }
-      }
-
-      .revision-history-diff {
-        padding-left: 40px;
-        color: $gray-900;
-        table-layout: fixed;
-      }
-    }
-
-    li {
-      position: relative;
-      list-style: none;
-    }
-  }
-
-  // compacted list
-  .revision-history-list-compact {
-    .revision-history-outer-contiguous-nodiff {
-      border-top: unset !important; // force unset border
-    }
-  }
-
-  // adjust
-  // this is for diff2html. hide page name from diff view
-  .d2h-file-header {
-    display: none;
-  }
-
-  .d2h-diff-tbody {
-    background-color: white;
-  }
-}
-
 /**
 /**
  * for table with handsontable modal button
  * for table with handsontable modal button
  */
  */

+ 1 - 0
src/client/styles/scss/style-app.scss

@@ -55,6 +55,7 @@
 @import 'page-path';
 @import 'page-path';
 @import 'page';
 @import 'page';
 @import 'page-presentation';
 @import 'page-presentation';
+@import 'page-history';
 @import 'search';
 @import 'search';
 @import 'shortcuts';
 @import 'shortcuts';
 @import 'sidebar';
 @import 'sidebar';

+ 4 - 41
src/server/models/page.js

@@ -46,21 +46,7 @@ const pageSchema = new mongoose.Schema({
   liker: [{ type: ObjectId, ref: 'User' }],
   liker: [{ type: ObjectId, ref: 'User' }],
   seenUsers: [{ type: ObjectId, ref: 'User' }],
   seenUsers: [{ type: ObjectId, ref: 'User' }],
   commentCount: { type: Number, default: 0 },
   commentCount: { type: Number, default: 0 },
-  extended: {
-    type: String,
-    default: '{}',
-    get(data) {
-      try {
-        return JSON.parse(data);
-      }
-      catch (e) {
-        return data;
-      }
-    },
-    set(data) {
-      return JSON.stringify(data);
-    },
-  },
+  slackChannels: { type: String },
   pageIdOnHackmd: String,
   pageIdOnHackmd: String,
   revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
   revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
   hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
   hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
@@ -426,33 +412,10 @@ module.exports = function(crowi) {
     return saved;
     return saved;
   };
   };
 
 
-  pageSchema.methods.getSlackChannel = function() {
-    const extended = this.get('extended');
-    if (!extended) {
-      return '';
-    }
-
-    return extended.slack || '';
-  };
-
-  pageSchema.methods.updateSlackChannel = function(slackChannel) {
-    const extended = this.extended;
-    extended.slack = slackChannel;
-
-    return this.updateExtended(extended);
-  };
+  pageSchema.methods.updateSlackChannels = function(slackChannels) {
+    this.slackChannels = slackChannels;
 
 
-  pageSchema.methods.updateExtended = function(extended) {
-    const page = this;
-    page.extended = extended;
-    return new Promise(((resolve, reject) => {
-      return page.save((err, doc) => {
-        if (err) {
-          return reject(err);
-        }
-        return resolve(doc);
-      });
-    }));
+    return this.save();
   };
   };
 
 
   pageSchema.methods.initLatestRevisionField = async function(revisionId) {
   pageSchema.methods.initLatestRevisionField = async function(revisionId) {

+ 4 - 2
src/server/routes/apiv3/app-settings.js

@@ -6,6 +6,7 @@ const debug = require('debug')('growi:routes:admin');
 
 
 const express = require('express');
 const express = require('express');
 
 
+const { pathUtils } = require('growi-commons');
 const { listLocaleIds } = require('@commons/util/locale-utils');
 const { listLocaleIds } = require('@commons/util/locale-utils');
 
 
 const router = express.Router();
 const router = express.Router();
@@ -156,7 +157,8 @@ module.exports = (crowi) => {
       body('fileUpload').isBoolean(),
       body('fileUpload').isBoolean(),
     ],
     ],
     siteUrlSetting: [
     siteUrlSetting: [
-      body('siteUrl').trim().matches(/^(https?:\/\/[^/]+|)$/).isURL({ require_tld: false }),
+      // https://regex101.com/r/5Xef8V/1
+      body('siteUrl').trim().matches(/^(https?:\/\/)/).isURL({ require_tld: false }),
     ],
     ],
     mailSetting: [
     mailSetting: [
       body('fromAddress').trim().if(value => value !== '').isEmail(),
       body('fromAddress').trim().if(value => value !== '').isEmail(),
@@ -334,7 +336,7 @@ module.exports = (crowi) => {
   router.put('/site-url-setting', loginRequiredStrictly, adminRequired, csrf, validator.siteUrlSetting, apiV3FormValidator, async(req, res) => {
   router.put('/site-url-setting', loginRequiredStrictly, adminRequired, csrf, validator.siteUrlSetting, apiV3FormValidator, async(req, res) => {
 
 
     const requestSiteUrlSettingParams = {
     const requestSiteUrlSettingParams = {
-      'app:siteUrl': req.body.siteUrl,
+      'app:siteUrl': pathUtils.removeTrailingSlash(req.body.siteUrl),
     };
     };
 
 
     try {
     try {

+ 1 - 1
src/server/routes/apiv3/pages.js

@@ -252,7 +252,7 @@ module.exports = (crowi) => {
     // user notification
     // user notification
     if (isSlackEnabled) {
     if (isSlackEnabled) {
       try {
       try {
-        const results = await userNotificationService.fire(createdPage, req.user, slackChannels, 'create', false);
+        const results = await userNotificationService.fire(createdPage, req.user, slackChannels, 'create');
         results.forEach((result) => {
         results.forEach((result) => {
           if (result.status === 'rejected') {
           if (result.status === 'rejected') {
             logger.error('Create user notification failed', result.reason);
             logger.error('Create user notification failed', result.reason);

+ 11 - 1
src/server/routes/apiv3/revisions.js

@@ -91,7 +91,17 @@ module.exports = (crowi) => {
    *            name: pageId
    *            name: pageId
    *            schema:
    *            schema:
    *              type: string
    *              type: string
-   *              description:  page id
+   *              description: page id
+   *          - in: query
+   *            name: page
+   *            description: selected page number
+   *            schema:
+   *              type: number
+   *          - in: query
+   *            name: limit
+   *            description: page item limit
+   *            schema:
+   *              type: number
    *        responses:
    *        responses:
    *          200:
    *          200:
    *            description: Return revisions belong to page
    *            description: Return revisions belong to page

+ 15 - 19
src/server/routes/comment.js

@@ -48,7 +48,10 @@ module.exports = function(crowi, app) {
   const Page = crowi.model('Page');
   const Page = crowi.model('Page');
   const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
   const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
   const ApiResponse = require('../util/apiResponse');
   const ApiResponse = require('../util/apiResponse');
+
   const globalNotificationService = crowi.getGlobalNotificationService();
   const globalNotificationService = crowi.getGlobalNotificationService();
+  const userNotificationService = crowi.getUserNotificationService();
+
   const { body } = require('express-validator');
   const { body } = require('express-validator');
   const mongoose = require('mongoose');
   const mongoose = require('mongoose');
   const ObjectId = mongoose.Types.ObjectId;
   const ObjectId = mongoose.Types.ObjectId;
@@ -253,8 +256,6 @@ module.exports = function(crowi, app) {
 
 
     res.json(ApiResponse.success({ comment: createdComment }));
     res.json(ApiResponse.success({ comment: createdComment }));
 
 
-    const path = page.path;
-
     // global notification
     // global notification
     try {
     try {
       await globalNotificationService.fire(GlobalNotificationSetting.EVENT.COMMENT, page, req.user, {
       await globalNotificationService.fire(GlobalNotificationSetting.EVENT.COMMENT, page, req.user, {
@@ -265,26 +266,21 @@ module.exports = function(crowi, app) {
       logger.error('Comment notification failed', err);
       logger.error('Comment notification failed', err);
     }
     }
 
 
-
     // slack notification
     // slack notification
     if (slackNotificationForm.isSlackEnabled) {
     if (slackNotificationForm.isSlackEnabled) {
-      const user = await User.findUserByUsername(req.user.username);
-      const channelsStr = slackNotificationForm.slackChannels || null;
-
-      page.updateSlackChannel(channelsStr).catch((err) => {
-        logger.error('Error occured in updating slack channels: ', err);
-      });
-
-      const channels = channelsStr != null ? channelsStr.split(',') : [null];
-
-      const promises = channels.map((chan) => {
-        return crowi.slack.postComment(createdComment, user, chan, path);
-      });
-
-      Promise.all(promises)
-        .catch((err) => {
-          logger.error('Error occured in sending slack notification: ', err);
+      const { slackChannels } = slackNotificationForm;
+
+      try {
+        const results = await userNotificationService.fire(page, req.user, slackChannels, 'comment', {}, createdComment);
+        results.forEach((result) => {
+          if (result.status === 'rejected') {
+            logger.error('Create user notification failed', result.reason);
+          }
         });
         });
+      }
+      catch (err) {
+        logger.error('Create user notification failed', err);
+      }
     }
     }
   };
   };
 
 

+ 24 - 51
src/server/routes/page.js

@@ -136,16 +136,16 @@ module.exports = function(crowi, app) {
   const User = crowi.model('User');
   const User = crowi.model('User');
   const Bookmark = crowi.model('Bookmark');
   const Bookmark = crowi.model('Bookmark');
   const PageTagRelation = crowi.model('PageTagRelation');
   const PageTagRelation = crowi.model('PageTagRelation');
-  const UpdatePost = crowi.model('UpdatePost');
   const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
   const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
   const ShareLink = crowi.model('ShareLink');
   const ShareLink = crowi.model('ShareLink');
 
 
   const ApiResponse = require('../util/apiResponse');
   const ApiResponse = require('../util/apiResponse');
   const getToday = require('../util/getToday');
   const getToday = require('../util/getToday');
 
 
-  const { slackNotificationService, configManager, xssService } = crowi;
+  const { configManager, xssService } = crowi;
   const interceptorManager = crowi.getInterceptorManager();
   const interceptorManager = crowi.getInterceptorManager();
   const globalNotificationService = crowi.getGlobalNotificationService();
   const globalNotificationService = crowi.getGlobalNotificationService();
+  const userNotificationService = crowi.getUserNotificationService();
 
 
   const XssOption = require('../../lib/service/xss/xssOption');
   const XssOption = require('../../lib/service/xss/xssOption');
   const Xss = require('../../lib/service/xss/index');
   const Xss = require('../../lib/service/xss/index');
@@ -194,37 +194,6 @@ module.exports = function(crowi, app) {
     };
     };
   }
   }
 
 
-  // user notification
-  // TODO create '/service/user-notification' module
-  /**
-   *
-   * @param {Page} page
-   * @param {User} user
-   * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
-   * @param {boolean} updateOrCreate
-   * @param {string} previousRevision
-   */
-  async function notifyToSlackByUser(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
-    await page.updateSlackChannel(slackChannelsStr)
-      .catch((err) => {
-        logger.error('Error occured in updating slack channels: ', err);
-      });
-
-
-    if (slackNotificationService.hasSlackConfig()) {
-      const slackChannels = slackChannelsStr != null ? slackChannelsStr.split(',') : [null];
-
-      const promises = slackChannels.map((chan) => {
-        return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
-      });
-
-      Promise.all(promises)
-        .catch((err) => {
-          logger.error('Error occured in sending slack notification: ', err);
-        });
-    }
-  }
-
   function addRenderVarsForPage(renderVars, page) {
   function addRenderVarsForPage(renderVars, page) {
     renderVars.page = page;
     renderVars.page = page;
     renderVars.revision = page.revision;
     renderVars.revision = page.revision;
@@ -268,10 +237,6 @@ module.exports = function(crowi, app) {
     renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
     renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
   }
   }
 
 
-  async function addRenderVarsForSlack(renderVars, page) {
-    renderVars.slack = await getSlackChannels(page);
-  }
-
   async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
   async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
     const SEENER_THRESHOLD = 10;
     const SEENER_THRESHOLD = 10;
 
 
@@ -349,7 +314,6 @@ module.exports = function(crowi, app) {
     portalPage = await portalPage.populateDataToShowRevision();
     portalPage = await portalPage.populateDataToShowRevision();
 
 
     addRenderVarsForPage(renderVars, portalPage);
     addRenderVarsForPage(renderVars, portalPage);
-    await addRenderVarsForSlack(renderVars, portalPage);
 
 
     const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
     const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
     renderVars.sharelinksNumber = sharelinksNumber;
     renderVars.sharelinksNumber = sharelinksNumber;
@@ -399,7 +363,6 @@ module.exports = function(crowi, app) {
     addRenderVarsForPage(renderVars, page);
     addRenderVarsForPage(renderVars, page);
     addRenderVarsForScope(renderVars, page);
     addRenderVarsForScope(renderVars, page);
 
 
-    await addRenderVarsForSlack(renderVars, page);
     await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
     await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
 
 
     const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
     const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
@@ -415,16 +378,6 @@ module.exports = function(crowi, app) {
     return res.render(view, renderVars);
     return res.render(view, renderVars);
   }
   }
 
 
-  const getSlackChannels = async(page) => {
-    if (page.extended.slack) {
-      return page.extended.slack;
-    }
-
-    const data = await UpdatePost.findSettingsByPath(page.path);
-    const channels = data.map((e) => { return e.channel }).join(', ');
-    return channels;
-  };
-
   actions.showTopPage = function(req, res) {
   actions.showTopPage = function(req, res) {
     return showTopPage(req, res);
     return showTopPage(req, res);
   };
   };
@@ -769,7 +722,17 @@ module.exports = function(crowi, app) {
 
 
     // user notification
     // user notification
     if (isSlackEnabled) {
     if (isSlackEnabled) {
-      await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
+      try {
+        const results = await userNotificationService.fire(createdPage, req.user, slackChannels, 'create');
+        results.forEach((result) => {
+          if (result.status === 'rejected') {
+            logger.error('Create user notification failed', result.reason);
+          }
+        });
+      }
+      catch (err) {
+        logger.error('Create user notification failed', err);
+      }
     }
     }
   };
   };
 
 
@@ -904,7 +867,17 @@ module.exports = function(crowi, app) {
 
 
     // user notification
     // user notification
     if (isSlackEnabled) {
     if (isSlackEnabled) {
-      await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
+      try {
+        const results = await userNotificationService.fire(page, req.user, slackChannels, 'update', { previousRevision });
+        results.forEach((result) => {
+          if (result.status === 'rejected') {
+            logger.error('Create user notification failed', result.reason);
+          }
+        });
+      }
+      catch (err) {
+        logger.error('Create user notification failed', err);
+      }
     }
     }
   };
   };
 
 

+ 5 - 5
src/server/service/page.js

@@ -151,7 +151,7 @@ class PageService {
       .addConditionToFilteringByViewer(user)
       .addConditionToFilteringByViewer(user)
       .query
       .query
       .lean()
       .lean()
-      .cursor();
+      .cursor({ batchSize: BULK_REINDEX_SIZE });
 
 
     const renameDescendants = this.renameDescendants.bind(this);
     const renameDescendants = this.renameDescendants.bind(this);
     const pageEvent = this.pageEvent;
     const pageEvent = this.pageEvent;
@@ -353,7 +353,7 @@ class PageService {
       .addConditionToFilteringByViewer(user)
       .addConditionToFilteringByViewer(user)
       .query
       .query
       .lean()
       .lean()
-      .cursor();
+      .cursor({ batchSize: BULK_REINDEX_SIZE });
 
 
     const duplicateDescendants = this.duplicateDescendants.bind(this);
     const duplicateDescendants = this.duplicateDescendants.bind(this);
     const pageEvent = this.pageEvent;
     const pageEvent = this.pageEvent;
@@ -488,7 +488,7 @@ class PageService {
       .addConditionToFilteringByViewer(user)
       .addConditionToFilteringByViewer(user)
       .query
       .query
       .lean()
       .lean()
-      .cursor();
+      .cursor({ batchSize: BULK_REINDEX_SIZE });
 
 
     const deleteDescendants = this.deleteDescendants.bind(this);
     const deleteDescendants = this.deleteDescendants.bind(this);
     let count = 0;
     let count = 0;
@@ -564,7 +564,7 @@ class PageService {
       .addConditionToFilteringByViewer(user)
       .addConditionToFilteringByViewer(user)
       .query
       .query
       .lean()
       .lean()
-      .cursor();
+      .cursor({ batchSize: BULK_REINDEX_SIZE });
 
 
     const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
     const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
     let count = 0;
     let count = 0;
@@ -690,7 +690,7 @@ class PageService {
       .addConditionToFilteringByViewer(user)
       .addConditionToFilteringByViewer(user)
       .query
       .query
       .lean()
       .lean()
-      .cursor();
+      .cursor({ batchSize: BULK_REINDEX_SIZE });
 
 
     const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
     const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
     let count = 0;
     let count = 0;

+ 1 - 1
src/server/service/search-delegator/elasticsearch.js

@@ -390,7 +390,7 @@ class ElasticsearchDelegator {
         { path: 'revision', model: 'Revision', select: 'body' },
         { path: 'revision', model: 'Revision', select: 'body' },
       ])
       ])
       .lean()
       .lean()
-      .cursor();
+      .cursor({ batchSize: BULK_REINDEX_SIZE });
 
 
     let skipped = 0;
     let skipped = 0;
     const thinOutStream = new Transform({
     const thinOutStream = new Transform({

+ 14 - 4
src/server/service/user-notification/index.js

@@ -19,13 +19,17 @@ class UserNotificationService {
    * @param {Page} page
    * @param {Page} page
    * @param {User} user
    * @param {User} user
    * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
    * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
-   * @param {boolean} updateOrCreate
+   * @param {string} mode 'create' or 'update' or 'comment'
    * @param {string} previousRevision
    * @param {string} previousRevision
+   * @param {Comment} comment
    */
    */
-  async fire(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
+  async fire(page, user, slackChannelsStr, mode, option, comment = {}) {
     const { slackNotificationService, slack } = this.crowi;
     const { slackNotificationService, slack } = this.crowi;
 
 
-    await page.updateSlackChannel(slackChannelsStr);
+    const opt = option || {};
+    const previousRevision = opt.previousRevision || '';
+
+    await page.updateSlackChannels(slackChannelsStr);
 
 
     if (!slackNotificationService.hasSlackConfig()) {
     if (!slackNotificationService.hasSlackConfig()) {
       throw new Error('slackNotificationService has not been set up');
       throw new Error('slackNotificationService has not been set up');
@@ -35,7 +39,13 @@ class UserNotificationService {
     const slackChannels = toArrayFromCsv(slackChannelsStr);
     const slackChannels = toArrayFromCsv(slackChannelsStr);
 
 
     const promises = slackChannels.map(async(chan) => {
     const promises = slackChannels.map(async(chan) => {
-      const res = await slack.postPage(page, user, chan, updateOrCreate, previousRevision);
+      let res;
+      if (mode === 'comment') {
+        res = await slack.postComment(comment, user, chan, page.path);
+      }
+      else {
+        res = await slack.postPage(page, user, chan, mode, previousRevision);
+      }
       if (res.status !== 'ok') {
       if (res.status !== 'ok') {
         throw new Error(`fail to send slack notification to #${chan} channel`);
         throw new Error(`fail to send slack notification to #${chan} channel`);
       }
       }

+ 2 - 2
src/server/views/widget/page_content.html

@@ -18,7 +18,7 @@
   data-page-is-deletable="{% if isDeletablePage() %}true{% else %}false{% endif %}"
   data-page-is-deletable="{% if isDeletablePage() %}true{% else %}false{% endif %}"
   data-page-is-not-creatable="false"
   data-page-is-not-creatable="false"
   data-page-is-able-to-delete-completely="{% if user.canDeleteCompletely(page.creator._id) %}true{% else %}false{% endif %}"
   data-page-is-able-to-delete-completely="{% if user.canDeleteCompletely(page.creator._id) %}true{% else %}false{% endif %}"
-  data-slack-channels="{{ slack|default('') }}"
+  data-slack-channels="{% if page %}{{ page.slackChannels }}{% endif %}"
   data-page-created-at="{% if page %}{{ page.createdAt|datetz('Y/m/d H:i:s') }}{% endif %}"
   data-page-created-at="{% if page %}{{ page.createdAt|datetz('Y/m/d H:i:s') }}{% endif %}"
   data-page-creator="{% if page && page.creator %}{{ page.creator|json }}{% endif %}"
   data-page-creator="{% if page && page.creator %}{{ page.creator|json }}{% endif %}"
   data-page-last-update-username="{% if page && page.lastUpdateUser %}{{ page.lastUpdateUser.name }}{% endif %}"
   data-page-last-update-username="{% if page && page.lastUpdateUser %}{{ page.lastUpdateUser.name }}{% endif %}"
@@ -36,7 +36,7 @@
 <div id="content-main" class="content-main d-flex"
 <div id="content-main" class="content-main d-flex"
   data-path="{{ encodeURI(path) }}"
   data-path="{{ encodeURI(path) }}"
   data-current-user="{% if user %}{{ user._id.toString() }}{% endif %}"
   data-current-user="{% if user %}{{ user._id.toString() }}{% endif %}"
-  data-slack-channels="{{ slack|default('') }}"
+  data-slack-channels="{% if page %}{{ page.slackChannels }}{% endif %}"
   data-page-is-deleted="{% if page.isDeleted() %}true{% else %}false{% endif %}"
   data-page-is-deleted="{% if page.isDeleted() %}true{% else %}false{% endif %}"
   data-page-has-children="{% if pages.length > 0 %}true{% else %}false{% endif %}"
   data-page-has-children="{% if pages.length > 0 %}true{% else %}false{% endif %}"
   >
   >

+ 4 - 23
src/test/models/page.test.js

@@ -93,10 +93,9 @@ describe('Page', () => {
         creator: testUser0,
         creator: testUser0,
       },
       },
       {
       {
-        path: '/page/for/extended',
+        path: '/page/child/without/parents',
         grant: Page.GRANT_PUBLIC,
         grant: Page.GRANT_PUBLIC,
         creator: testUser0,
         creator: testUser0,
-        extended: { hoge: 1 },
       },
       },
       {
       {
         path: '/grant/groupacl',
         path: '/grant/groupacl',
@@ -266,24 +265,6 @@ describe('Page', () => {
     });
     });
   });
   });
 
 
-  describe('Extended field', () => {
-    describe('Slack Channel.', () => {
-      test('should be empty', async() => {
-        const page = await Page.findOne({ path: '/page/for/extended' });
-        expect(page.extended.hoge).toEqual(1);
-        expect(page.getSlackChannel()).toEqual('');
-      });
-
-      test('set slack channel and should get it and should keep hoge ', async() => {
-        let page = await Page.findOne({ path: '/page/for/extended' });
-        await page.updateSlackChannel('slack-channel1');
-        page = await Page.findOne({ path: '/page/for/extended' });
-        expect(page.extended.hoge).toEqual(1);
-        expect(page.getSlackChannel()).toEqual('slack-channel1');
-      });
-    });
-  });
-
   describe('.findPage', () => {
   describe('.findPage', () => {
     describe('findByIdAndViewer', () => {
     describe('findByIdAndViewer', () => {
       test('should find page (public)', async() => {
       test('should find page (public)', async() => {
@@ -341,7 +322,7 @@ describe('Page', () => {
       expect(result.length).toEqual(1);
       expect(result.length).toEqual(1);
       // assert paths
       // assert paths
       const pagePaths = result.map((page) => { return page.path });
       const pagePaths = result.map((page) => { return page.path });
-      expect(pagePaths).toContainEqual('/page/for/extended');
+      expect(pagePaths).toContainEqual('/page/child/without/parents');
     });
     });
 
 
     test('can retrieve descendants of /page1', async() => {
     test('can retrieve descendants of /page1', async() => {
@@ -370,7 +351,7 @@ describe('Page', () => {
       expect(result.length).toEqual(1);
       expect(result.length).toEqual(1);
       // assert paths
       // assert paths
       const pagePaths = result.map((page) => { return page.path });
       const pagePaths = result.map((page) => { return page.path });
-      expect(pagePaths).toContainEqual('/page/for/extended');
+      expect(pagePaths).toContainEqual('/page/child/without/parents');
     });
     });
 
 
     test('can retrieve only descendants of /page1', async() => {
     test('can retrieve only descendants of /page1', async() => {
@@ -398,7 +379,7 @@ describe('Page', () => {
       expect(result.length).toEqual(4);
       expect(result.length).toEqual(4);
       // assert paths
       // assert paths
       const pagePaths = result.map((page) => { return page.path });
       const pagePaths = result.map((page) => { return page.path });
-      expect(pagePaths).toContainEqual('/page/for/extended');
+      expect(pagePaths).toContainEqual('/page/child/without/parents');
       expect(pagePaths).toContainEqual('/page1');
       expect(pagePaths).toContainEqual('/page1');
       expect(pagePaths).toContainEqual('/page1/child1');
       expect(pagePaths).toContainEqual('/page1/child1');
       expect(pagePaths).toContainEqual('/page2');
       expect(pagePaths).toContainEqual('/page2');