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

Merge pull request #5932 from weseek/master

Release v5.0.8
Yuki Takei 3 лет назад
Родитель
Сommit
94105d3cc7
100 измененных файлов с 1506 добавлено и 1817 удалено
  1. 1 1
      lerna.json
  2. 1 1
      package.json
  3. 13 11
      packages/app/package.json
  4. 1 0
      packages/app/resource/Contributor.js
  5. 1 0
      packages/app/resource/locales/en_US/translation.json
  6. 1 0
      packages/app/resource/locales/ja_JP/translation.json
  7. 2 1
      packages/app/resource/locales/zh_CN/translation.json
  8. 0 4
      packages/app/src/client/app.jsx
  9. 4 0
      packages/app/src/client/base.jsx
  10. 2 122
      packages/app/src/client/legacy/crowi.js
  11. 0 31
      packages/app/src/client/services/AppContainer.js
  12. 0 4
      packages/app/src/client/services/CommentContainer.js
  13. 1 3
      packages/app/src/client/services/ContextExtractor.tsx
  14. 0 14
      packages/app/src/client/services/EditorContainer.js
  15. 12 22
      packages/app/src/client/services/PageContainer.js
  16. 0 77
      packages/app/src/client/services/PersonalContainer.js
  17. 15 17
      packages/app/src/client/util/GrowiRenderer.js
  18. 4 4
      packages/app/src/client/util/editor.ts
  19. 2 8
      packages/app/src/client/util/interceptor/detach-code-blocks.js
  20. 6 10
      packages/app/src/client/util/interceptor/drawio-interceptor.js
  21. 0 4
      packages/app/src/client/util/markdown-it/footernote.js
  22. 1 2
      packages/app/src/client/util/markdown-it/header-line-number.js
  23. 1 5
      packages/app/src/client/util/markdown-it/header-with-edit-link.js
  24. 1 3
      packages/app/src/client/util/markdown-it/header.js
  25. 1 5
      packages/app/src/client/util/markdown-it/table-with-handsontable-button.js
  26. 0 4
      packages/app/src/client/util/markdown-it/table.js
  27. 5 12
      packages/app/src/client/util/markdown-it/toc-and-anchor.js
  28. 11 5
      packages/app/src/components/Admin/UserGroupDetail/UserGroupUserFormByInput.jsx
  29. 3 2
      packages/app/src/components/Common/Dropdown/PageItemControl.tsx
  30. 5 5
      packages/app/src/components/CreateTemplateModal.jsx
  31. 0 108
      packages/app/src/components/Drawio.jsx
  32. 97 0
      packages/app/src/components/Drawio.tsx
  33. 4 12
      packages/app/src/components/Fab.jsx
  34. 9 10
      packages/app/src/components/Me/ImageCropModal.jsx
  35. 0 197
      packages/app/src/components/Me/ProfileImageSettings.jsx
  36. 188 0
      packages/app/src/components/Me/ProfileImageSettings.tsx
  37. 51 53
      packages/app/src/components/Navbar/GrowiContextualSubNavigation.tsx
  38. 9 10
      packages/app/src/components/Navbar/GrowiNavbar.tsx
  39. 3 7
      packages/app/src/components/Navbar/GrowiSubNavigation.tsx
  40. 8 8
      packages/app/src/components/Navbar/SubNavButtons.tsx
  41. 7 9
      packages/app/src/components/NotAvailableForGuest.jsx
  42. 37 9
      packages/app/src/components/Page.jsx
  43. 10 10
      packages/app/src/components/Page/DisplaySwitcher.tsx
  44. 0 72
      packages/app/src/components/Page/NotFoundAlert.tsx
  45. 3 8
      packages/app/src/components/Page/RevisionBody.jsx
  46. 5 7
      packages/app/src/components/Page/TrashPageAlert.jsx
  47. 1 0
      packages/app/src/components/PageAccessoriesModal.tsx
  48. 30 18
      packages/app/src/components/PageAttachment.jsx
  49. 19 12
      packages/app/src/components/PageComment/Comment.jsx
  50. 31 10
      packages/app/src/components/PageComment/CommentEditor.jsx
  51. 4 1
      packages/app/src/components/PageCreateModal.jsx
  52. 0 440
      packages/app/src/components/PageEditor.jsx
  53. 435 0
      packages/app/src/components/PageEditor.tsx
  54. 42 49
      packages/app/src/components/PageEditor/ConflictDiffModal.tsx
  55. 49 30
      packages/app/src/components/PageEditor/EditorNavbarBottom.tsx
  56. 13 5
      packages/app/src/components/PageEditor/Preview.tsx
  57. 6 5
      packages/app/src/components/PageEditorByHackmd.jsx
  58. 1 1
      packages/app/src/components/PageHistory.jsx
  59. 3 1
      packages/app/src/components/PageList/PageList.tsx
  60. 1 0
      packages/app/src/components/PageList/PageListItemL.tsx
  61. 8 1
      packages/app/src/components/PagePresentationModal.jsx
  62. 32 54
      packages/app/src/components/PageStatusAlert.jsx
  63. 7 14
      packages/app/src/components/SavePageControls.jsx
  64. 26 32
      packages/app/src/components/SearchPage/SearchResultContent.tsx
  65. 21 14
      packages/app/src/components/Sidebar/Tag.tsx
  66. 1 0
      packages/app/src/components/SlackNotification.tsx
  67. 13 4
      packages/app/src/components/TableOfContents.jsx
  68. 13 24
      packages/app/src/components/TagCloudBox.tsx
  69. 2 2
      packages/app/src/components/TagList.tsx
  70. 11 0
      packages/app/src/interfaces/attachment.ts
  71. 3 0
      packages/app/src/interfaces/user-trigger-notification.ts
  72. 4 0
      packages/app/src/interfaces/user.ts
  73. 4 4
      packages/app/src/server/models/attachment.js
  74. 3 2
      packages/app/src/server/models/bookmark.js
  75. 2 1
      packages/app/src/server/models/external-account.js
  76. 2 4
      packages/app/src/server/models/in-app-notification.ts
  77. 2 3
      packages/app/src/server/models/page.ts
  78. 2 2
      packages/app/src/server/models/revision.js
  79. 3 2
      packages/app/src/server/models/share-link.js
  80. 2 1
      packages/app/src/server/models/subscription.ts
  81. 3 3
      packages/app/src/server/models/update-post.ts
  82. 2 1
      packages/app/src/server/models/user-group-relation.js
  83. 4 3
      packages/app/src/server/models/user-group.ts
  84. 6 8
      packages/app/src/server/models/user-registration-order.ts
  85. 4 6
      packages/app/src/server/models/user.js
  86. 4 4
      packages/app/src/server/routes/apiv3/page.js
  87. 6 1
      packages/app/src/server/routes/attachment.js
  88. 71 71
      packages/app/src/server/service/file-uploader/aws.ts
  89. 18 8
      packages/app/src/server/service/import.js
  90. 14 6
      packages/app/src/server/service/page.ts
  91. 3 1
      packages/app/src/server/service/search-delegator/elasticsearch.ts
  92. 0 11
      packages/app/src/server/service/user-notification/index.ts
  93. 0 34
      packages/app/src/server/util/middlewares.js
  94. 0 1
      packages/app/src/server/views/layout-growi/identical-path-page.html
  95. 0 1
      packages/app/src/server/views/layout-growi/not_found.html
  96. 0 2
      packages/app/src/server/views/widget/page_content.html
  97. 7 10
      packages/app/src/stores/context.tsx
  98. 27 6
      packages/app/src/stores/editor.tsx
  99. 14 5
      packages/app/src/stores/page.tsx
  100. 2 2
      packages/app/src/stores/ui.tsx

+ 1 - 1
lerna.json

@@ -1,7 +1,7 @@
 {
   "npmClient": "yarn",
   "useWorkspaces": true,
-  "version": "5.0.7",
+  "version": "5.0.8-RC.0",
   "packages": [
     "packages/*"
   ]

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "growi",
-  "version": "5.0.7",
+  "version": "5.0.8-RC.0",
   "description": "Team collaboration software using markdown",
   "tags": [
     "wiki",

+ 13 - 11
packages/app/package.json

@@ -1,6 +1,6 @@
 {
   "name": "@growi/app",
-  "version": "5.0.7",
+  "version": "5.0.8-RC.0",
   "license": "MIT",
   "scripts": {
     "//// for production": "",
@@ -11,7 +11,7 @@
     "clean": "npx -y shx rm -rf dist transpiled",
     "prebuild": "yarn cross-env NODE_ENV=production run-p clean resources:*",
     "postbuild": "npx -y shx mv transpiled/src dist && npx -y shx cp -r src/server/views dist/server/ && npx -y shx rm -rf transpiled",
-    "server": "yarn cross-env NODE_ENV=production node -r dotenv-flow/config --expose_gc dist/server/app.js",
+    "server": "yarn cross-env NODE_ENV=production node -r dotenv-flow/config dist/server/app.js",
     "server:ci": "yarn server --ci",
     "preserver": "yarn cross-env NODE_ENV=production yarn migrate",
     "migrate": "node -r dotenv-flow/config node_modules/.bin/migrate-mongo up",
@@ -19,7 +19,7 @@
     "dev": "run-p dev:client dev:server",
     "dev:client": "yarn cross-env NODE_ENV=development webpack --config config/webpack.dev.js --progress --watch",
     "dev:client:nowatch": "yarn cross-env NODE_ENV=development webpack --config config/webpack.dev.js",
-    "dev:server": "yarn cross-env NODE_ENV=development ts-node-dev --inspect --expose-gc -r tsconfig-paths/register -r dotenv-flow/config --transpile-only src/server/app.ts",
+    "dev:server": "yarn cross-env NODE_ENV=development ts-node-dev --inspect -r tsconfig-paths/register -r dotenv-flow/config --transpile-only src/server/app.ts",
     "predev:client": "yarn cross-env NODE_ENV=development run-p resources:*",
     "predev:server": "yarn cross-env NODE_ENV=development yarn dev:migrate:up",
     "dev:migrate-mongo": "yarn cross-env NODE_ENV=development yarn ts-node node_modules/.bin/migrate-mongo",
@@ -57,16 +57,18 @@
     "string-width": "5.0.0 or above exports only ESM."
   },
   "dependencies": {
+    "@aws-sdk/client-s3": "^3.58.0",
+    "@aws-sdk/s3-request-presigner": "^3.58.0",
     "@browser-bunyan/console-formatted-stream": "^1.6.2",
     "@elastic/elasticsearch6": "npm:@elastic/elasticsearch@^6.8.8",
     "@elastic/elasticsearch7": "npm:@elastic/elasticsearch@^7.17.0",
     "@godaddy/terminus": "^4.9.0",
     "@google-cloud/storage": "^5.8.5",
-    "@growi/codemirror-textlint": "^5.0.7",
-    "@growi/plugin-attachment-refs": "^5.0.7",
-    "@growi/plugin-lsx": "^5.0.7",
-    "@growi/plugin-pukiwiki-like-linker": "^5.0.7",
-    "@growi/slack": "^5.0.7",
+    "@growi/codemirror-textlint": "^5.0.8-RC.0",
+    "@growi/plugin-attachment-refs": "^5.0.8-RC.0",
+    "@growi/plugin-lsx": "^5.0.8-RC.0",
+    "@growi/plugin-pukiwiki-like-linker": "^5.0.8-RC.0",
+    "@growi/slack": "^5.0.8-RC.0",
     "@promster/express": "^7.0.2",
     "@promster/server": "^7.0.4",
     "@slack/events-api": "^3.0.0",
@@ -97,6 +99,7 @@
     "esa-node": "^0.2.2",
     "escape-string-regexp": "=4.0.0",
     "eslint-plugin-regex": "^1.8.0",
+    "expose-gc": "^1.0.0",
     "express": "^4.16.1",
     "express-bunyan-logger": "^1.3.3",
     "express-mongo-sanitize": "^2.1.0",
@@ -143,7 +146,6 @@
     "react-dnd-html5-backend": "^14.1.0",
     "react-image-crop": "^8.3.0",
     "react-multiline-clamp": "^2.0.0",
-    "react-tagcloud": "^2.1.1",
     "reconnecting-websocket": "^4.4.0",
     "redis": "^3.0.2",
     "rimraf": "^3.0.0",
@@ -167,7 +169,7 @@
   },
   "devDependencies": {
     "@alienfast/i18next-loader": "^1.1.4",
-    "@growi/ui": "^5.0.7",
+    "@growi/ui": "^5.0.8-RC.0",
     "@handsontable/react": "=2.1.0",
     "@types/compression": "^1.7.0",
     "@types/express": "^4.17.11",
@@ -188,7 +190,6 @@
     "diff2html": "^3.1.2",
     "eazy-logger": "^3.1.0",
     "emoji-mart": "npm:panta82-emoji-mart@^3.0.1",
-    "markdown-it-emoji-mart": "^0.1.1",
     "eslint-plugin-cypress": "^2.12.1",
     "eslint-plugin-regex": "^1.8.0",
     "file-loader": "^5.0.2",
@@ -206,6 +207,7 @@
     "markdown-it-blockdiag": "^1.1.1",
     "markdown-it-drawio-viewer": "^1.3.1",
     "markdown-it-emoji": "^1.4.0",
+    "markdown-it-emoji-mart": "^0.1.1",
     "markdown-it-footnote": "^3.0.1",
     "markdown-it-mathjax": "^2.0.0",
     "markdown-it-named-headers": "^0.0.4",

+ 1 - 0
packages/app/resource/Contributor.js

@@ -41,6 +41,7 @@ const contributors = [
           { name: 'N1koge' },
           { name: 'Ertai87' },
           { name: 'takayuki-t' },
+          { name: 'ayaka0417' },
           { name: 'zahmis' },
           { name: 'takeru0001' },
           { name: 'Shu Katabe' },

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

@@ -147,6 +147,7 @@
   "Shareable link": "Shareable link",
   "The whitelist of registration permission E-mail address": "The whitelist of registration permission E-mail address",
   "Add tags for this page": "Add tags for this page",
+  "tag_list": "Tag list",
   "popular_tags": "Popular tags",
   "Check All tags": "check all tags",
   "You have no tag, You can set tags on pages": "You have no tag, You can set tags on pages",

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

@@ -146,6 +146,7 @@
   "Shareable link": "このページの共有用URL",
   "The whitelist of registration permission E-mail address": "登録許可メールアドレスの<br>ホワイトリスト",
   "Add tags for this page": "タグを付ける",
+  "tag_list": "タグ一覧",
   "popular_tags": "人気のタグ",
   "Check All tags": "全てのタグを見る",
   "You have no tag, You can set tags on pages": "使用中のタグがありません",

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

@@ -155,6 +155,7 @@
 	"Shareable link": "可分享链接",
 	"The whitelist of registration permission E-mail address": "注册许可电子邮件地址的白名单",
 	"Add tags for this page": "添加标签",
+  "tag_list": "标签列表",
   "popular_tags": "流行标签",
   "Check All tags": "检查所有标签",
 	"You have no tag, You can set tags on pages": "你没有标签,可以在页面上设置标签",
@@ -524,7 +525,7 @@
 	"template": {
 		"modal_label": {
 			"Create/Edit Template Page": "创建/编辑模板页",
-			"Create template under": "在下面创建模板页:<br/><code><small>%s</small></code>"
+			"Create template under": "在下面创建模板页"
 		},
 		"option_label": {
 			"create/edit": "创建/编辑模板页。",

+ 0 - 4
packages/app/src/client/app.jsx

@@ -34,7 +34,6 @@ import NotFoundPage from '../components/NotFoundPage';
 import Page from '../components/Page';
 import DisplaySwitcher from '../components/Page/DisplaySwitcher';
 import FixPageGrantAlert from '../components/Page/FixPageGrantAlert';
-import NotFoundAlert from '../components/Page/NotFoundAlert';
 import RedirectedAlert from '../components/Page/RedirectedAlert';
 import ShareLinkAlert from '../components/Page/ShareLinkAlert';
 import TrashPageAlert from '../components/Page/TrashPageAlert';
@@ -117,9 +116,6 @@ Object.assign(componentMappings, {
 
   'share-link-alert': <ShareLinkAlert />,
   'redirected-alert': <RedirectedAlert />,
-  'not-found-alert': <NotFoundAlert
-    isGuestUserMode={appContainer.isGuestUser}
-  />,
 });
 
 // additional definitions if data exists

+ 4 - 0
packages/app/src/client/base.jsx

@@ -1,5 +1,7 @@
 import React from 'react';
 
+import EventEmitter from 'events';
+
 import AppContainer from '~/client/services/AppContainer';
 import SocketIoContainer from '~/client/services/SocketIoContainer';
 import { DescendantsPageListModal } from '~/components/DescendantsPageListModal';
@@ -28,6 +30,8 @@ if (!window) {
 const xss = new Xss();
 window.xss = xss;
 
+window.globalEmitter = new EventEmitter();
+
 // create unstated container instance
 const appContainer = new AppContainer();
 // eslint-disable-next-line no-unused-vars

+ 2 - 122
packages/app/src/client/legacy/crowi.js

@@ -12,38 +12,8 @@ if (!window) {
 }
 window.Crowi = Crowi;
 
-/**
- * set 'data-caret-line' attribute that will be processed when 'shown.bs.tab' event fired
- * @param {number} line
- */
-Crowi.setCaretLineData = function(line) {
-  const { appContainer } = window;
-  const pageEditorDom = document.querySelector('#page-editor');
-  pageEditorDom.setAttribute('data-caret-line', line);
-};
-
-/**
- * invoked when;
- *
- * 1. 'shown.bs.tab' event fired
- */
-Crowi.setCaretLineAndFocusToEditor = function() {
-  // get 'data-caret-line' attributes
-  const pageEditorDom = document.querySelector('#page-editor');
-
-  if (pageEditorDom == null) {
-    return;
-  }
-
-  const { appContainer } = window;
-  const editorContainer = appContainer.getContainer('EditorContainer');
-  const line = pageEditorDom.getAttribute('data-caret-line') || 0;
-  editorContainer.setCaretLine(+line);
-  // reset data-caret-line attribute
-  pageEditorDom.removeAttribute('data-caret-line');
-
-  // focus
-  editorContainer.focusToEditor();
+Crowi.setCaretLine = function(line) {
+  window.globalEmitter.emit('setCaretLine', line);
 };
 
 // original: middleware.swigFilter
@@ -55,39 +25,6 @@ Crowi.userPicture = function(user) {
   return user.image || '/images/icons/user.svg';
 };
 
-Crowi.modifyScrollTop = function() {
-  const offset = 10;
-
-  const hash = window.location.hash;
-  if (hash === '') {
-    return;
-  }
-
-  const pageHeader = document.querySelector('#page-header');
-  if (!pageHeader) {
-    return;
-  }
-  const pageHeaderRect = pageHeader.getBoundingClientRect();
-
-  const sectionHeader = Crowi.findSectionHeader(hash);
-  if (sectionHeader === null) {
-    return;
-  }
-
-  let timeout = 0;
-  if (window.scrollY === 0) {
-    timeout = 200;
-  }
-  setTimeout(() => {
-    const sectionHeaderRect = sectionHeader.getBoundingClientRect();
-    if (sectionHeaderRect.top >= pageHeaderRect.bottom) {
-      return;
-    }
-
-    window.scrollTo(0, (window.scrollY - pageHeaderRect.height - offset));
-  }, timeout);
-};
-
 Crowi.initClassesByOS = function() {
   // add classes to cmd-key by OS
   const platform = navigator.platform.toLowerCase();
@@ -112,63 +49,6 @@ Crowi.initClassesByOS = function() {
   });
 };
 
-window.addEventListener('load', () => {
-  const crowi = window.crowi;
-  if (crowi && crowi.users && crowi.users.length !== 0) {
-    const totalUsers = crowi.users.length;
-    const $listLiker = $('.page-list-liker');
-    $listLiker.each((i, liker) => {
-      const count = $(liker).data('count') || 0;
-      if (count / totalUsers > 0.05) {
-        $(liker).addClass('popular-page-high');
-        // 5%
-      }
-      else if (count / totalUsers > 0.02) {
-        $(liker).addClass('popular-page-mid');
-        // 2%
-      }
-      else if (count / totalUsers > 0.005) {
-        $(liker).addClass('popular-page-low');
-        // 0.5%
-      }
-    });
-    const $listSeer = $('.page-list-seer');
-    $listSeer.each((i, seer) => {
-      const count = $(seer).data('count') || 0;
-      if (count / totalUsers > 0.10) {
-        // 10%
-        $(seer).addClass('popular-page-high');
-      }
-      else if (count / totalUsers > 0.05) {
-        // 5%
-        $(seer).addClass('popular-page-mid');
-      }
-      else if (count / totalUsers > 0.02) {
-        // 2%
-        $(seer).addClass('popular-page-low');
-      }
-    });
-  }
-
-  blinkSectionHeaderAtBoot();
-
-  Crowi.modifyScrollTop();
-  Crowi.initClassesByOS();
-});
-
-window.addEventListener('hashchange', (e) => {
-  Crowi.modifyScrollTop();
-
-  // hash on page
-  if (window.location.hash) {
-    if (window.location.hash === '#edit') {
-      Crowi.setCaretLineAndFocusToEditor();
-    }
-    // else if (window.location.hash === '#hackmd') {
-    // }
-  }
-});
-
 // adjust min-height of page for print temporarily
 window.onbeforeprint = function() {
   $('#page-wrapper').css('min-height', '0px');

+ 0 - 31
packages/app/src/client/services/AppContainer.js

@@ -26,12 +26,6 @@ export default class AppContainer extends Container {
       this.currentUser = JSON.parse(currentUserElem.textContent);
     }
 
-    const isSharedPageElem = document.getElementById('is-shared-page');
-
-    // check what kind of user
-    this.isGuestUser = this.currentUser == null;
-    this.isSharedUser = isSharedPageElem != null && this.currentUser == null;
-
     const userLocaleId = this.currentUser?.lang;
     this.i18n = i18nFactory(userLocaleId);
 
@@ -149,10 +143,6 @@ export default class AppContainer extends Container {
       throw new Error('The specified instance must not be null');
     }
 
-    if (this.componentInstances[id] != null) {
-      throw new Error('The specified instance couldn\'t register because the same id has already been registered');
-    }
-
     this.componentInstances[id] = instance;
   }
 
@@ -186,25 +176,4 @@ export default class AppContainer extends Container {
     return renderer;
   }
 
-
-  launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
-    let targetComponent;
-    switch (componentKind) {
-      case 'page':
-        targetComponent = this.getComponentInstance('Page');
-        break;
-    }
-    targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
-  }
-
-  launchDrawioModal(componentKind, beginLineNumber, endLineNumber) {
-    let targetComponent;
-    switch (componentKind) {
-      case 'page':
-        targetComponent = this.getComponentInstance('Page');
-        break;
-    }
-    targetComponent.launchDrawioModal(beginLineNumber, endLineNumber);
-  }
-
 }

+ 0 - 4
packages/app/src/client/services/CommentContainer.js

@@ -30,10 +30,6 @@ export default class CommentContainer extends Container {
 
     this.state = {
       comments: [],
-
-      // settings shared among all of CommentEditor
-      isSlackEnabled: false,
-      slackChannels: mainContent.getAttribute('data-slack-channels') || '',
     };
 
     this.retrieveComments = this.retrieveComments.bind(this);

+ 1 - 3
packages/app/src/client/services/ContextExtractor.tsx

@@ -16,7 +16,7 @@ import {
   useIsDeleted, useIsNotCreatable, useIsTrashPage, useIsUserPage, useLastUpdateUsername,
   useCurrentPageId, usePageIdOnHackmd, usePageUser, useCurrentPagePath, useRevisionCreatedAt, useRevisionId, useRevisionIdHackmdSynced,
   useShareLinkId, useShareLinksNumber, useTemplateTagData, useCurrentUpdatedAt, useCreator, useRevisionAuthor, useCurrentUser, useTargetAndAncestors,
-  useSlackChannels, useNotFoundTargetPathOrId, useIsSearchPage, useIsForbidden, useIsIdenticalPath, useHasParent,
+  useNotFoundTargetPathOrId, useIsSearchPage, useIsForbidden, useIsIdenticalPath, useHasParent,
   useIsAclEnabled, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsEnabledAttachTitleHeader, useIsNotFoundPermalink,
   useDefaultIndentSize, useIsIndentSizeForced,
 } from '../../stores/context';
@@ -85,7 +85,6 @@ const ContextExtractorOnce: FC = () => {
   const targetAndAncestors = JSON.parse(document.getElementById('growi-pagetree-target-and-ancestors')?.textContent || jsonNull);
   const notFoundTargetPathOrId = JSON.parse(notFoundContentForPt?.getAttribute('data-not-found-target-path-or-id') || jsonNull);
   const isNotFoundPermalink = JSON.parse(notFoundContent?.getAttribute('data-is-not-found-permalink') || jsonNull);
-  const slackChannels = mainContent?.getAttribute('data-slack-channels') || '';
   const isSearchPage = document.getElementById('search-page') != null;
 
   const grant = +(mainContent?.getAttribute('data-page-grant') || 1);
@@ -158,7 +157,6 @@ const ContextExtractorOnce: FC = () => {
   useIsDeviceSmallerThanMd();
 
   // Editor
-  useSlackChannels(slackChannels);
   useSelectedGrant(grant);
   useSelectedGrantGroupId(grantGroupId);
   useSelectedGrantGroupName(grantGroupName);

+ 0 - 14
packages/app/src/client/services/EditorContainer.js

@@ -59,20 +59,6 @@ export default class EditorContainer extends Container {
     }
   }
 
-  setCaretLine(line) {
-    const pageEditor = this.appContainer.getComponentInstance('PageEditor');
-    if (pageEditor != null) {
-      pageEditor.setCaretLine(line);
-    }
-  }
-
-  focusToEditor() {
-    const pageEditor = this.appContainer.getComponentInstance('PageEditor');
-    if (pageEditor != null) {
-      pageEditor.focusToEditor();
-    }
-  }
-
   getCurrentOptionsToSave() {
     const opt = {
       pageTags: this.state.tags,

+ 12 - 22
packages/app/src/client/services/PageContainer.js

@@ -52,7 +52,6 @@ export default class PageContainer extends Container {
       revisionId,
       revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
       path,
-      tocHtml: '',
 
       createdAt: mainContent.getAttribute('data-page-created-at'),
       // please use useCurrentUpdatedAt instead
@@ -101,13 +100,12 @@ export default class PageContainer extends Container {
     }
 
     const { interceptorManager } = this.appContainer;
-    interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(appContainer), 10); // process as soon as possible
-    interceptorManager.addInterceptor(new DrawioInterceptor(appContainer), 20);
-    interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(appContainer), 900); // process as late as possible
+    interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(), 10); // process as soon as possible
+    interceptorManager.addInterceptor(new DrawioInterceptor(), 20);
+    interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(), 900); // process as late as possible
 
     this.initStateMarkdown();
 
-    this.setTocHtml = this.setTocHtml.bind(this);
     this.save = this.save.bind(this);
 
     this.emitJoinPageRoomRequest = this.emitJoinPageRoomRequest.bind(this);
@@ -194,12 +192,6 @@ export default class PageContainer extends Container {
     this.setState(newState);
   }
 
-  async setTocHtml(tocHtml) {
-    if (this.state.tocHtml !== tocHtml) {
-      this.setState({ tocHtml });
-    }
-  }
-
   /**
    * save success handler
    * @param {object} page Page instance
@@ -225,13 +217,11 @@ export default class PageContainer extends Container {
     }
     this.setState(newState);
 
-    // PageEditor component
-    const pageEditor = this.appContainer.getComponentInstance('PageEditor');
-    if (pageEditor != null) {
-      if (editorMode !== EditorMode.Editor) {
-        pageEditor.updateEditorValue(newState.markdown);
-      }
+    // Update PageEditor component
+    if (editorMode !== EditorMode.Editor) {
+      window.globalEmitter.emit('updateEditorValue', newState.markdown);
     }
+
     // PageEditorByHackmd component
     const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
     if (pageEditorByHackmd != null) {
@@ -279,7 +269,7 @@ export default class PageContainer extends Container {
     let { revisionId } = this.state;
     const options = Object.assign({}, optionsToSave);
 
-    if (editorMode === 'hackmd') {
+    if (editorMode === EditorMode.HackMD) {
       // set option to sync
       options.isSyncRevisionToHackmd = true;
       revisionId = this.state.revisionIdHackmdSynced;
@@ -314,7 +304,7 @@ export default class PageContainer extends Container {
     const options = Object.assign({}, optionsToSave);
 
     let markdown;
-    if (editorMode === 'hackmd') {
+    if (editorMode === EditorMode.HackMD) {
       const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
       markdown = await pageEditorByHackmd.getMarkdown();
       // set option to sync
@@ -459,7 +449,6 @@ export default class PageContainer extends Container {
 
     const { pageId, remoteRevisionId, path } = this.state;
     const editorContainer = this.appContainer.getContainer('EditorContainer');
-    const pageEditor = this.appContainer.getComponentInstance('PageEditor');
     const options = editorContainer.getCurrentOptionsToSave();
     const optionsToSave = Object.assign({}, options);
 
@@ -468,8 +457,9 @@ export default class PageContainer extends Container {
     editorContainer.clearDraft(path);
     this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
 
-    if (pageEditor != null) {
-      pageEditor.updateEditorValue(markdown);
+    // Update PageEditor component
+    if (editorMode !== EditorMode.Editor) {
+      window.globalEmitter.emit('updateEditorValue', markdown);
     }
 
     editorContainer.setState({ tags: res.tags });

+ 0 - 77
packages/app/src/client/services/PersonalContainer.js

@@ -8,8 +8,6 @@ import { apiv3Get, apiv3Put } from '../util/apiv3-client';
 // eslint-disable-next-line no-unused-vars
 const logger = loggerFactory('growi:services:PersonalContainer');
 
-const DEFAULT_IMAGE = '/images/icons/user.svg';
-
 /**
  * Service container for personal settings page (PersonalSettings.jsx)
  * @extends {Container} unstated Container
@@ -29,8 +27,6 @@ export default class PersonalContainer extends Container {
       isEmailPublished: false,
       lang: 'en_US',
       isGravatarEnabled: false,
-      isUploadedPicture: false,
-      uploadedPictureSrc: this.getUploadedPictureSrc(this.appContainer.currentUser),
       externalAccounts: [],
       apiToken: '',
       slackMemberId: '',
@@ -69,25 +65,6 @@ export default class PersonalContainer extends Container {
     }
   }
 
-  /**
-   * define a function for uploaded picture
-   */
-  getUploadedPictureSrc(user) {
-    if (user == null) {
-      return DEFAULT_IMAGE;
-    }
-    if (user.image) {
-      this.setState({ isUploadedPicture: true });
-      return user.image;
-    }
-    if (user.imageAttachment != null) {
-      this.setState({ isUploadedPicture: true });
-      return user.imageAttachment.filePathProxied;
-    }
-
-    return DEFAULT_IMAGE;
-  }
-
   /**
    * retrieve external accounts that linked me
    */
@@ -178,60 +155,6 @@ export default class PersonalContainer extends Container {
     }
   }
 
-  /**
-   * Update profile image
-   * @memberOf PersonalContainer
-   */
-  async updateProfileImage() {
-    try {
-      const response = await apiv3Put('/personal-setting/image-type', {
-        isGravatarEnabled: this.state.isGravatarEnabled,
-      });
-      const { userData } = response.data;
-      this.setState({
-        isGravatarEnabled: userData.isGravatarEnabled,
-      });
-    }
-    catch (err) {
-      this.setState({ retrieveError: err });
-      logger.error(err);
-      throw new Error('Failed to update profile image');
-    }
-  }
-
-  /**
-   * Upload image
-   */
-  async uploadAttachment(file) {
-    try {
-      const formData = new FormData();
-      formData.append('file', file);
-      formData.append('_csrf', this.appContainer.csrfToken);
-      const response = await apiPost('/attachments.uploadProfileImage', formData);
-      this.setState({ isUploadedPicture: true, uploadedPictureSrc: response.attachment.filePathProxied });
-    }
-    catch (err) {
-      this.setState({ retrieveError: err });
-      logger.error(err);
-      throw new Error('Failed to upload profile image');
-    }
-  }
-
-  /**
-   * Delete image
-   */
-  async deleteProfileImage() {
-    try {
-      await apiPost('/attachments.removeProfileImage', { _csrf: this.appContainer.csrfToken });
-      this.setState({ isUploadedPicture: false, uploadedPictureSrc: DEFAULT_IMAGE });
-    }
-    catch (err) {
-      this.setState({ retrieveError: err });
-      logger.error(err);
-      throw new Error('Failed to delete profile image');
-    }
-  }
-
   /**
    * Associate LDAP account
    */

+ 15 - 17
packages/app/src/client/util/GrowiRenderer.js

@@ -40,9 +40,9 @@ export default class GrowiRenderer {
     }
     else {
       this.preProcessors = [
-        new EasyGrid(appContainer),
-        new Linker(appContainer),
-        new CsvToTable(appContainer),
+        new EasyGrid(),
+        new Linker(),
+        new CsvToTable(),
         new XssFilter(appContainer),
       ];
       this.postProcessors = [
@@ -70,10 +70,10 @@ export default class GrowiRenderer {
     this.markdownItConfigurers = [
       new LinkerByRelativePathConfigurer(appContainer),
       new TaskListsConfigurer(appContainer),
-      new HeaderConfigurer(appContainer),
-      new EmojiConfigurer(appContainer),
+      new HeaderConfigurer(),
+      new EmojiConfigurer(),
       new MathJaxConfigurer(appContainer),
-      new DrawioViewerConfigurer(appContainer),
+      new DrawioViewerConfigurer(),
       new PlantUMLConfigurer(appContainer),
       new BlockdiagConfigurer(appContainer),
     ];
@@ -81,29 +81,27 @@ export default class GrowiRenderer {
     // add configurers according to mode
     switch (mode) {
       case 'page': {
-        const pageContainer = appContainer.getContainer('PageContainer');
-
         this.markdownItConfigurers = this.markdownItConfigurers.concat([
-          new FooternoteConfigurer(appContainer),
-          new TocAndAnchorConfigurer(appContainer, pageContainer.setTocHtml),
-          new HeaderLineNumberConfigurer(appContainer),
-          new HeaderWithEditLinkConfigurer(appContainer),
-          new TableWithHandsontableButtonConfigurer(appContainer),
+          new FooternoteConfigurer(),
+          new TocAndAnchorConfigurer(),
+          new HeaderLineNumberConfigurer(),
+          new HeaderWithEditLinkConfigurer(),
+          new TableWithHandsontableButtonConfigurer(),
         ]);
         break;
       }
       case 'editor':
         this.markdownItConfigurers = this.markdownItConfigurers.concat([
-          new FooternoteConfigurer(appContainer),
-          new HeaderLineNumberConfigurer(appContainer),
-          new TableConfigurer(appContainer),
+          new FooternoteConfigurer(),
+          new HeaderLineNumberConfigurer(),
+          new TableConfigurer(),
         ]);
         break;
       // case 'comment':
       //   break;
       default:
         this.markdownItConfigurers = this.markdownItConfigurers.concat([
-          new TableConfigurer(appContainer),
+          new TableConfigurer(),
         ]);
         break;
     }

+ 4 - 4
packages/app/src/client/util/editor.ts

@@ -5,8 +5,8 @@ type OptionsToSave = {
   slackChannels: string;
   grant: number;
   pageTags: string[] | null;
-  grantUserGroupId: string | null;
-  grantUserGroupName: string | null;
+  grantUserGroupId?: string | null;
+  grantUserGroupName?: string | null;
 };
 
 // TODO: Remove editorContainer upon migration to SWR
@@ -14,8 +14,8 @@ export const getOptionsToSave = (
     isSlackEnabled: boolean,
     slackChannels: string,
     grant: number,
-    grantUserGroupId: string | null,
-    grantUserGroupName: string | null,
+    grantUserGroupId: string | null | undefined,
+    grantUserGroupName: string | null | undefined,
     editorContainer: EditorContainer,
 ): OptionsToSave => {
   const optionsToSave = editorContainer.getCurrentOptionsToSave();

+ 2 - 8
packages/app/src/client/util/interceptor/detach-code-blocks.js

@@ -15,12 +15,9 @@ class DetachCodeBlockUtil {
  */
 export class DetachCodeBlockInterceptor extends BasicInterceptor {
 
-  constructor(crowi) {
+  constructor() {
     super();
     this.logger = loggerFactory('growi:interceptor:DetachCodeBlockInterceptor');
-
-    this.crowi = crowi;
-    this.crowiForJquery = crowi.getCrowiForJquery();
   }
 
   /**
@@ -94,12 +91,9 @@ export class DetachCodeBlockInterceptor extends BasicInterceptor {
  */
 export class RestoreCodeBlockInterceptor extends BasicInterceptor {
 
-  constructor(crowi) {
+  constructor() {
     super();
     this.logger = loggerFactory('growi:interceptor:DetachCodeBlockInterceptor');
-
-    this.crowi = crowi;
-    this.crowiForJquery = crowi.getCrowiForJquery();
   }
 
   /**

+ 6 - 10
packages/app/src/client/util/interceptor/drawio-interceptor.js

@@ -3,7 +3,6 @@ import React from 'react';
 
 import { BasicInterceptor } from '@growi/core';
 import ReactDOM from 'react-dom';
-import { Provider } from 'unstated';
 
 import Drawio from '~/components/Drawio';
 
@@ -14,11 +13,10 @@ import Drawio from '~/components/Drawio';
  */
 export class DrawioInterceptor extends BasicInterceptor {
 
-  constructor(appContainer) {
+  constructor() {
     super();
 
     this.previousPreviewContext = null;
-    this.appContainer = appContainer;
   }
 
   /**
@@ -125,13 +123,11 @@ export class DrawioInterceptor extends BasicInterceptor {
   renderReactDOM(drawioMapEntry, elem, isPreview) {
     ReactDOM.render(
       // eslint-disable-next-line react/jsx-filename-extension
-      <Provider inject={[this.appContainer]}>
-        <Drawio
-          drawioContent={drawioMapEntry.contentHtml}
-          isPreview={isPreview}
-          rangeLineNumberOfMarkdown={drawioMapEntry.rangeLineNumberOfMarkdown}
-        />
-      </Provider>,
+      <Drawio
+        drawioContent={drawioMapEntry.contentHtml}
+        isPreview={isPreview}
+        rangeLineNumberOfMarkdown={drawioMapEntry.rangeLineNumberOfMarkdown}
+      />,
       elem,
     );
   }

+ 0 - 4
packages/app/src/client/util/markdown-it/footernote.js

@@ -1,9 +1,5 @@
 export default class FooternoteConfigurer {
 
-  constructor(crowi) {
-    this.crowi = crowi;
-  }
-
   configure(md) {
     md.use(require('markdown-it-footnote'));
   }

+ 1 - 2
packages/app/src/client/util/markdown-it/header-line-number.js

@@ -1,7 +1,6 @@
 export default class HeaderLineNumberConfigurer {
 
-  constructor(crowi) {
-    this.crowi = crowi;
+  constructor() {
     this.firstLine = 0;
   }
 

+ 1 - 5
packages/app/src/client/util/markdown-it/header-with-edit-link.js

@@ -1,13 +1,9 @@
 export default class HeaderWithEditLinkConfigurer {
 
-  constructor(crowi) {
-    this.crowi = crowi;
-  }
-
   configure(md) {
     md.renderer.rules.heading_close = (tokens, idx) => {
       return `<span class="revision-head-edit-button">
-                <a href="#edit" onClick="Crowi.setCaretLineData(parseInt(this.parentNode.parentNode.dataset.line, 10))">
+                <a href="#edit" onClick="Crowi.setCaretLine(parseInt(this.parentNode.parentNode.dataset.line, 10))">
                   <i class="icon-note"></i>
                 </a>
               </span></${tokens[idx].tag}>`;

+ 1 - 3
packages/app/src/client/util/markdown-it/header.js

@@ -1,8 +1,6 @@
 export default class HeaderConfigurer {
 
-  constructor(crowi) {
-    this.crowi = crowi;
-
+  constructor() {
     this.injectRevisionHeadClass = this.injectRevisionHeadClass.bind(this);
   }
 

+ 1 - 5
packages/app/src/client/util/markdown-it/table-with-handsontable-button.js

@@ -1,15 +1,11 @@
 export default class TableWithHandsontableButtonConfigurer {
 
-  constructor(crowi) {
-    this.crowi = crowi;
-  }
-
   configure(md) {
     md.renderer.rules.table_open = (tokens, idx) => {
       const beginLine = tokens[idx].map[0] + 1;
       const endLine = tokens[idx].map[1];
       // eslint-disable-next-line max-len
-      return `<div class="editable-with-handsontable"><button class="handsontable-modal-trigger" onClick="crowi.launchHandsontableModal('page', ${beginLine}, ${endLine})"><i class="icon-note"></i></button><table class="table table-bordered">`;
+      return `<div class="editable-with-handsontable"><button class="handsontable-modal-trigger" onClick="globalEmitter.emit('launchHandsontableModal', ${beginLine}, ${endLine})"><i class="icon-note"></i></button><table class="table table-bordered">`;
     };
 
     md.renderer.rules.table_close = (tokens, idx) => {

+ 0 - 4
packages/app/src/client/util/markdown-it/table.js

@@ -1,9 +1,5 @@
 export default class TableConfigurer {
 
-  constructor(crowi) {
-    this.crowi = crowi;
-  }
-
   configure(md) {
     md.renderer.rules.table_open = (tokens, idx) => {
       return '<table class="table table-bordered">';

+ 5 - 12
packages/app/src/client/util/markdown-it/toc-and-anchor.js

@@ -5,11 +5,6 @@ import { emojiMartData } from './emoji-mart-data';
 
 export default class TocAndAnchorConfigurer {
 
-  constructor(crowi, setHtml) {
-    this.crowi = crowi;
-    this.setHtml = setHtml;
-  }
-
   configure(md) {
     md.use(markdownItEmojiMart, { defs: emojiMartData })
       .use(markdownItToc, {
@@ -21,13 +16,11 @@ export default class TocAndAnchorConfigurer {
       });
 
     // set toc render function
-    if (this.setHtml != null) {
-      md.set({
-        tocCallback: (tocMarkdown, tocArray, tocHtml) => {
-          this.setHtml(tocHtml);
-        },
-      });
-    }
+    md.set({
+      tocCallback: (tocMarkdown, tocArray, tocHtml) => {
+        window.globalEmitter.emit('renderTocHtml', tocHtml);
+      },
+    });
   }
 
 }

+ 11 - 5
packages/app/src/components/Admin/UserGroupDetail/UserGroupUserFormByInput.jsx

@@ -1,15 +1,17 @@
 import React from 'react';
-import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
 
+import { UserPicture } from '@growi/ui';
+import PropTypes from 'prop-types';
 import { AsyncTypeahead } from 'react-bootstrap-typeahead';
+import { withTranslation } from 'react-i18next';
 import { debounce } from 'throttle-debounce';
-import { UserPicture } from '@growi/ui';
-import { withUnstatedContainers } from '../../UnstatedUtils';
-import AppContainer from '~/client/services/AppContainer';
+
 import AdminUserGroupDetailContainer from '~/client/services/AdminUserGroupDetailContainer';
+import AppContainer from '~/client/services/AppContainer';
 import { toastSuccess, toastError } from '~/client/util/apiNotification';
 
+import { withUnstatedContainers } from '../../UnstatedUtils';
+
 class UserGroupUserFormByInput extends React.Component {
 
   constructor(props) {
@@ -44,12 +46,16 @@ class UserGroupUserFormByInput extends React.Component {
 
     try {
       await adminUserGroupDetailContainer.addUserByUsername(userName);
+      await adminUserGroupDetailContainer.init();
+      await adminUserGroupDetailContainer.closeUserGroupUserModal();
       toastSuccess(`Added "${this.xss.process(userName)}" to "${this.xss.process(userGroup.name)}"`);
       this.setState({ inputUser: '' });
     }
     catch (err) {
       toastError(new Error(`Unable to add "${this.xss.process(userName)}" to "${this.xss.process(userGroup.name)}"`));
     }
+
+
   }
 
   validateForm() {

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

@@ -40,6 +40,7 @@ type CommonProps = {
 
   additionalMenuItemRenderer?: React.FunctionComponent<AdditionalMenuItemsRendererProps>,
   isInstantRename?: boolean,
+  alignRight?: boolean,
 }
 
 
@@ -55,7 +56,7 @@ const PageItemControlDropdownMenu = React.memo((props: DropdownMenuProps): JSX.E
     pageId, isLoading,
     pageInfo, isEnableActions, forceHideMenuItems,
     onClickBookmarkMenuItem, onClickRenameMenuItem, onClickDuplicateMenuItem, onClickDeleteMenuItem, onClickRevertMenuItem,
-    additionalMenuItemRenderer: AdditionalMenuItems, isInstantRename,
+    additionalMenuItemRenderer: AdditionalMenuItems, isInstantRename, alignRight,
   } = props;
 
 
@@ -205,7 +206,7 @@ const PageItemControlDropdownMenu = React.memo((props: DropdownMenuProps): JSX.E
   }
 
   return (
-    <DropdownMenu positionFixed modifiers={{ preventOverflow: { boundariesElement: undefined } }}>
+    <DropdownMenu positionFixed modifiers={{ preventOverflow: { boundariesElement: undefined } }} right={alignRight}>
       {contents}
     </DropdownMenu>
   );

+ 5 - 5
packages/app/src/components/CreateTemplateModal.jsx

@@ -1,10 +1,9 @@
 import React from 'react';
-import PropTypes from 'prop-types';
-
-import { Modal, ModalHeader, ModalBody } from 'reactstrap';
 
-import { withTranslation } from 'react-i18next';
 import { pathUtils } from '@growi/core';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+import { Modal, ModalHeader, ModalBody } from 'reactstrap';
 import urljoin from 'url-join';
 
 
@@ -30,6 +29,7 @@ const CreateTemplateModal = (props) => {
         </div>
         <div className="card-footer text-center">
           <a
+            data-testid={`template-button-${target}`}
             href={generateUrl(label)}
             className="btn btn-sm btn-primary"
             id={`template-button-${target}`}
@@ -42,7 +42,7 @@ const CreateTemplateModal = (props) => {
   }
 
   return (
-    <Modal isOpen={props.isOpen} toggle={props.onClose} className="grw-create-page">
+    <Modal isOpen={props.isOpen} toggle={props.onClose} data-testid="page-template-modal" className="grw-create-page">
       <ModalHeader tag="h4" toggle={props.onClose} className="bg-primary text-light">
         {t('template.modal_label.Create/Edit Template Page')}
       </ModalHeader>

+ 0 - 108
packages/app/src/components/Drawio.jsx

@@ -1,108 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-
-import { debounce } from 'throttle-debounce';
-
-import { withTranslation } from 'react-i18next';
-
-import AppContainer from '~/client/services/AppContainer';
-
-import { withUnstatedContainers } from './UnstatedUtils';
-
-import NotAvailableForGuest from './NotAvailableForGuest';
-
-class Drawio extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.drawioContainer = React.createRef();
-
-    this.style = {
-      borderRadius: 3,
-      border: '1px solid #d7d7d7',
-      margin: '20px 0',
-    };
-
-    this.isPreview = this.props.isPreview;
-    this.drawioContent = this.props.drawioContent;
-
-    this.onEdit = this.onEdit.bind(this);
-
-    // create debounced method for rendering Drawio
-    this.renderDrawioWithDebounce = debounce(200, this.renderDrawio);
-  }
-
-  onEdit() {
-    const { appContainer, rangeLineNumberOfMarkdown } = this.props;
-    const { beginLineNumber, endLineNumber } = rangeLineNumberOfMarkdown;
-    appContainer.launchDrawioModal('page', beginLineNumber, endLineNumber);
-  }
-
-  componentDidMount() {
-    const DrawioViewer = window.GraphViewer;
-    if (DrawioViewer != null) {
-      this.renderDrawio();
-    }
-    else {
-      this.renderDrawioWithDebounce();
-    }
-  }
-
-  renderDrawio() {
-    const DrawioViewer = window.GraphViewer;
-    if (DrawioViewer != null) {
-      const mxgraphs = this.drawioContainer.getElementsByClassName('mxgraph');
-      if (mxgraphs.length > 0) {
-        // GROWI では、mxgraph element は最初のものをレンダリングする前提とする
-        const div = mxgraphs[0];
-
-        if (div != null) {
-          div.innerHTML = '';
-          DrawioViewer.createViewerForElement(div);
-        }
-      }
-    }
-    else {
-      this.renderDrawioWithDebounce();
-    }
-  }
-
-  renderContents() {
-    return this.drawioContent;
-  }
-
-  render() {
-    return (
-      <div className="editable-with-drawio position-relative">
-        { !this.isPreview && (
-          <NotAvailableForGuest>
-            <button type="button" className="drawio-iframe-trigger position-absolute btn btn-outline-secondary" onClick={this.onEdit}>
-              <i className="icon-note mr-1"></i>{this.props.t('Edit')}
-            </button>
-          </NotAvailableForGuest>
-        ) }
-        <div
-          className="drawio"
-          style={this.style}
-          ref={(c) => { this.drawioContainer = c }}
-          // eslint-disable-next-line react/no-danger
-          dangerouslySetInnerHTML={{ __html: this.renderContents() }}
-        >
-        </div>
-      </div>
-    );
-  }
-
-}
-
-Drawio.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.object.isRequired,
-
-  drawioContent: PropTypes.any.isRequired,
-  isPreview: PropTypes.bool,
-  rangeLineNumberOfMarkdown: PropTypes.object.isRequired,
-};
-
-export default withTranslation()(withUnstatedContainers(Drawio, [AppContainer]));

+ 97 - 0
packages/app/src/components/Drawio.tsx

@@ -0,0 +1,97 @@
+import React, {
+  useCallback, useEffect, useMemo, useRef,
+} from 'react';
+
+import EventEmitter from 'events';
+
+import { useTranslation } from 'react-i18next';
+import { debounce } from 'throttle-debounce';
+
+import NotAvailableForGuest from './NotAvailableForGuest';
+
+
+declare let window: {
+  globalEmitter: EventEmitter,
+  GraphViewer: {
+    createViewerForElement: (Element) => void,
+  };
+};
+
+type Props = {
+  drawioContent: string,
+  rangeLineNumberOfMarkdown: { beginLineNumber: number, endLineNumber: number },
+  isPreview?: boolean,
+}
+
+const Drawio = (props: Props): JSX.Element => {
+
+  const { t } = useTranslation();
+
+  const { drawioContent, rangeLineNumberOfMarkdown, isPreview } = props;
+
+  // const { open: openDrawioModal } = useDrawioModalForPage();
+
+  const drawioContainerRef = useRef<HTMLDivElement>(null);
+
+  const editButtonClickHandler = useCallback(() => {
+    const { beginLineNumber, endLineNumber } = rangeLineNumberOfMarkdown;
+    window.globalEmitter.emit('launchDrawioModal', beginLineNumber, endLineNumber);
+  }, [rangeLineNumberOfMarkdown]);
+
+  const renderDrawio = useCallback(() => {
+    if (drawioContainerRef.current == null) {
+      return;
+    }
+
+    const mxgraphs = drawioContainerRef.current.getElementsByClassName('mxgraph');
+    if (mxgraphs.length > 0) {
+      // GROWI では、mxgraph element は最初のものをレンダリングする前提とする
+      const div = mxgraphs[0];
+
+      if (div != null) {
+        div.innerHTML = '';
+        window.GraphViewer.createViewerForElement(div);
+      }
+    }
+  }, []);
+
+  const renderDrawioWithDebounce = useMemo(() => debounce(200, renderDrawio), [renderDrawio]);
+
+  const { GraphViewer } = window;
+  useEffect(() => {
+    if (GraphViewer == null) {
+      return;
+    }
+
+    renderDrawioWithDebounce();
+  }, [GraphViewer, renderDrawioWithDebounce]);
+
+  return (
+    <div className="editable-with-drawio position-relative">
+      { !isPreview && (
+        <NotAvailableForGuest>
+          <button type="button" className="drawio-iframe-trigger position-absolute btn btn-outline-secondary" onClick={editButtonClickHandler}>
+            <i className="icon-note mr-1"></i>{t('Edit')}
+          </button>
+        </NotAvailableForGuest>
+      ) }
+      <div
+        className="drawio"
+        style={
+          {
+            borderRadius: 3,
+            border: '1px solid #d7d7d7',
+            margin: '20px 0',
+          }
+        }
+        ref={drawioContainerRef}
+        // eslint-disable-next-line react/no-danger
+        dangerouslySetInnerHTML={{ __html: drawioContent }}
+      >
+      </div>
+    </div>
+  );
+
+};
+
+export default Drawio;

+ 4 - 12
packages/app/src/components/Fab.jsx

@@ -1,24 +1,20 @@
 import React, { useState, useCallback, useEffect } from 'react';
 
-import PropTypes from 'prop-types';
 import StickyEvents from 'sticky-events';
 
 
-import AppContainer from '~/client/services/AppContainer';
 import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
-import { useCurrentPagePath } from '~/stores/context';
+import { useCurrentPagePath, useCurrentUser } from '~/stores/context';
 import { usePageCreateModal } from '~/stores/modal';
 import loggerFactory from '~/utils/logger';
 
 import CreatePageIcon from './Icons/CreatePageIcon';
 import ReturnTopIcon from './Icons/ReturnTopIcon';
-import { withUnstatedContainers } from './UnstatedUtils';
 
 const logger = loggerFactory('growi:cli:Fab');
 
-const Fab = (props) => {
-  const { appContainer } = props;
-  const { currentUser } = appContainer;
+const Fab = () => {
+  const { data: currentUser } = useCurrentUser();
 
   const { open: openCreateModal } = usePageCreateModal();
   const { data: currentPath = '' } = useCurrentPagePath();
@@ -85,8 +81,4 @@ const Fab = (props) => {
 
 };
 
-Fab.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-};
-
-export default withUnstatedContainers(Fab, [AppContainer]);
+export default Fab;

+ 9 - 10
packages/app/src/components/Me/ImageCropModal.jsx

@@ -1,20 +1,20 @@
 import React from 'react';
-import PropTypes from 'prop-types';
-import canvasToBlob from 'async-canvas-to-blob';
 
+import canvasToBlob from 'async-canvas-to-blob';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+import ReactCrop from 'react-image-crop';
 import {
   Modal,
   ModalHeader,
   ModalBody,
   ModalFooter,
 } from 'reactstrap';
-import { withTranslation } from 'react-i18next';
-import ReactCrop from 'react-image-crop';
-import loggerFactory from '~/utils/logger';
-import AppContainer from '~/client/services/AppContainer';
-import { withUnstatedContainers } from '../UnstatedUtils';
+
 import 'react-image-crop/dist/ReactCrop.css';
 import { toastError } from '~/client/util/apiNotification';
+import loggerFactory from '~/utils/logger';
+
 
 const logger = loggerFactory('growi:ImageCropModal');
 
@@ -113,12 +113,11 @@ class ImageCropModal extends React.Component {
 /**
  * Wrapper component for using unstated
  */
-const ProfileImageFormWrapper = withUnstatedContainers(ImageCropModal, [AppContainer]);
 ImageCropModal.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   show: PropTypes.bool.isRequired,
   src: PropTypes.string,
   onModalClose: PropTypes.func.isRequired,
   onCropCompleted: PropTypes.func.isRequired,
 };
-export default withTranslation()(ProfileImageFormWrapper);
+
+export default withTranslation()(ImageCropModal);

+ 0 - 197
packages/app/src/components/Me/ProfileImageSettings.jsx

@@ -1,197 +0,0 @@
-import React from 'react';
-
-import md5 from 'md5';
-import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
-
-import AppContainer from '~/client/services/AppContainer';
-import PersonalContainer from '~/client/services/PersonalContainer';
-import { toastSuccess, toastError } from '~/client/util/apiNotification';
-
-import { withUnstatedContainers } from '../UnstatedUtils';
-
-
-import ImageCropModal from './ImageCropModal';
-
-class ProfileImageSettings extends React.Component {
-
-  constructor(appContainer) {
-    super();
-
-    this.state = {
-      show: false,
-      src: null,
-    };
-
-    this.imageRef = null;
-    this.onSelectFile = this.onSelectFile.bind(this);
-    this.onClickDeleteBtn = this.onClickDeleteBtn.bind(this);
-    this.hideModal = this.hideModal.bind(this);
-    this.cancelModal = this.cancelModal.bind(this);
-    this.onCropCompleted = this.onCropCompleted.bind(this);
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t, personalContainer } = this.props;
-
-    try {
-      await personalContainer.updateProfileImage();
-      toastSuccess(t('toaster.update_successed', { target: t('Set Profile Image') }));
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  generateGravatarSrc() {
-    const email = this.props.personalContainer.state.email || '';
-    const hash = md5(email.trim().toLowerCase());
-    return `https://gravatar.com/avatar/${hash}`;
-  }
-
-  onSelectFile(e) {
-    if (e.target.files && e.target.files.length > 0) {
-      const reader = new FileReader();
-      reader.addEventListener('load', () => this.setState({ src: reader.result }));
-      reader.readAsDataURL(e.target.files[0]);
-      this.setState({ show: true });
-    }
-  }
-
-  /**
-   * @param {object} croppedImage cropped profile image for upload
-   */
-  async onCropCompleted(croppedImage) {
-    const { t, personalContainer } = this.props;
-    try {
-      await personalContainer.uploadAttachment(croppedImage);
-      toastSuccess(t('toaster.update_successed', { target: t('Current Image') }));
-    }
-    catch (err) {
-      toastError(err);
-    }
-    this.hideModal();
-  }
-
-  async onClickDeleteBtn() {
-    const { t, personalContainer } = this.props;
-    try {
-      await personalContainer.deleteProfileImage();
-      toastSuccess(t('toaster.update_successed', { target: t('Current Image') }));
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  showModal() {
-    this.setState({ show: true });
-  }
-
-  hideModal() {
-    this.setState({ show: false });
-  }
-
-  cancelModal() {
-    this.hideModal();
-  }
-
-  render() {
-    const { t, personalContainer } = this.props;
-    const { uploadedPictureSrc, isGravatarEnabled, isUploadedPicture } = personalContainer.state;
-
-    return (
-      <React.Fragment>
-        <div className="row">
-          <div className="col-md-6 col-12 mb-3 mb-md-0">
-            <h4>
-              <div className="custom-control custom-radio radio-primary">
-                <input
-                  type="radio"
-                  id="radioGravatar"
-                  className="custom-control-input"
-                  form="formImageType"
-                  name="imagetypeForm[isGravatarEnabled]"
-                  checked={isGravatarEnabled}
-                  onChange={() => { personalContainer.changeIsGravatarEnabled(true) }}
-                />
-                <label className="custom-control-label" htmlFor="radioGravatar">
-                  <img src="https://gravatar.com/avatar/00000000000000000000000000000000?s=24" data-hide-in-vrt /> Gravatar
-                </label>
-                <a href="https://gravatar.com/">
-                  <small><i className="icon-arrow-right-circle" aria-hidden="true"></i></small>
-                </a>
-              </div>
-            </h4>
-            <img src={this.generateGravatarSrc()} width="64" data-hide-in-vrt />
-          </div>
-
-          <div className="col-md-6 col-12">
-            <h4>
-              <div className="custom-control custom-radio radio-primary">
-                <input
-                  type="radio"
-                  id="radioUploadPicture"
-                  className="custom-control-input"
-                  form="formImageType"
-                  name="imagetypeForm[isGravatarEnabled]"
-                  checked={!isGravatarEnabled}
-                  onChange={() => { personalContainer.changeIsGravatarEnabled(false) }}
-                />
-                <label className="custom-control-label" htmlFor="radioUploadPicture">
-                  { t('Upload Image') }
-                </label>
-              </div>
-            </h4>
-            <div className="row mb-3">
-              <label className="col-sm-4 col-12 col-form-label text-left">
-                { t('Current Image') }
-              </label>
-              <div className="col-sm-8 col-12">
-                {uploadedPictureSrc && (<p><img src={uploadedPictureSrc} className="picture picture-lg rounded-circle" id="settingUserPicture" /></p>)}
-                {isUploadedPicture && <button type="button" className="btn btn-danger" onClick={this.onClickDeleteBtn}>{ t('Delete Image') }</button>}
-              </div>
-            </div>
-            <div className="row">
-              <label className="col-sm-4 col-12 col-form-label text-left">
-                {t('Upload new image')}
-              </label>
-              <div className="col-sm-8 col-12">
-                <input type="file" onChange={this.onSelectFile} name="profileImage" accept="image/*" />
-              </div>
-            </div>
-          </div>
-        </div>
-
-        <ImageCropModal
-          show={this.state.show}
-          src={this.state.src}
-          onModalClose={this.cancelModal}
-          onCropCompleted={this.onCropCompleted}
-        />
-
-        <div className="row my-3">
-          <div className="offset-4 col-5">
-            <button type="button" className="btn btn-primary" onClick={this.onClickSubmit} disabled={personalContainer.state.retrieveError != null}>
-              {t('Update')}
-            </button>
-          </div>
-        </div>
-
-      </React.Fragment>
-    );
-  }
-
-}
-
-
-const ProfileImageSettingsWrapper = withUnstatedContainers(ProfileImageSettings, [AppContainer, PersonalContainer]);
-
-ProfileImageSettings.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  personalContainer: PropTypes.instanceOf(PersonalContainer).isRequired,
-};
-
-export default withTranslation()(ProfileImageSettingsWrapper);

+ 188 - 0
packages/app/src/components/Me/ProfileImageSettings.tsx

@@ -0,0 +1,188 @@
+import React, { useCallback, useState } from 'react';
+
+
+import { useTranslation } from 'react-i18next';
+
+import AppContainer from '~/client/services/AppContainer';
+import { toastSuccess, toastError } from '~/client/util/apiNotification';
+import { apiPost } from '~/client/util/apiv1-client';
+import { apiv3Put } from '~/client/util/apiv3-client';
+import { useCurrentUser } from '~/stores/context';
+import { generateGravatarSrc, GRAVATAR_DEFAULT } from '~/utils/gravatar';
+
+import { withUnstatedContainers } from '../UnstatedUtils';
+
+import ImageCropModal from './ImageCropModal';
+
+const DEFAULT_IMAGE = '/images/icons/user.svg';
+
+
+type Props = {
+  appContainer: AppContainer,
+}
+
+const ProfileImageSettings = (props: Props): JSX.Element => {
+  const { t } = useTranslation();
+
+  const { appContainer } = props;
+
+  const { data: currentUser } = useCurrentUser();
+
+  const [isGravatarEnabled, setGravatarEnabled] = useState(currentUser?.isGravatarEnabled);
+  const [uploadedPictureSrc, setUploadedPictureSrc] = useState(() => {
+    if (typeof currentUser?.imageAttachment === 'string') {
+      return currentUser?.image;
+    }
+    return currentUser?.imageAttachment?.filePathProxied ?? currentUser?.image;
+  });
+
+  const [showImageCropModal, setShowImageCropModal] = useState(false);
+  const [imageCropSrc, setImageCropSrc] = useState<string|ArrayBuffer|null>(null);
+
+  const selectFileHandler = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+    if (e.target.files == null || e.target.files.length === 0) {
+      return;
+    }
+
+    const reader = new FileReader();
+    reader.addEventListener('load', () => setImageCropSrc(reader.result));
+    reader.readAsDataURL(e.target.files[0]);
+
+    setShowImageCropModal(true);
+  }, []);
+
+  const cropCompletedHandler = useCallback(async(croppedImage) => {
+    try {
+      const formData = new FormData();
+      formData.append('file', croppedImage);
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      formData.append('_csrf', appContainer.csrfToken!);
+      const response = await apiPost('/attachments.uploadProfileImage', formData);
+
+      toastSuccess(t('toaster.update_successed', { target: t('Current Image') }));
+
+      // eslint-disable-next-line @typescript-eslint/no-explicit-any
+      setUploadedPictureSrc((response as any).attachment.filePathProxied);
+
+      // close modal
+      setShowImageCropModal(false);
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [appContainer.csrfToken, t]);
+
+  const deleteImageHandler = useCallback(async() => {
+    try {
+      await apiPost('/attachments.removeProfileImage');
+
+      setUploadedPictureSrc(undefined);
+      toastSuccess(t('toaster.update_successed', { target: t('Current Image') }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [t]);
+
+  const submit = useCallback(async() => {
+    try {
+      const response = await apiv3Put('/personal-setting/image-type', { isGravatarEnabled });
+
+      const { userData } = response.data;
+      setGravatarEnabled(userData.isGravatarEnabled);
+
+      toastSuccess(t('toaster.update_successed', { target: t('Set Profile Image') }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [isGravatarEnabled, t]);
+
+  if (currentUser == null) {
+    return <></>;
+  }
+
+  return (
+    <>
+      <div className="row">
+        <div className="col-md-6 col-12 mb-3 mb-md-0">
+          <h4>
+            <div className="custom-control custom-radio radio-primary">
+              <input
+                type="radio"
+                id="radioGravatar"
+                className="custom-control-input"
+                form="formImageType"
+                name="imagetypeForm[isGravatarEnabled]"
+                checked={isGravatarEnabled}
+                onChange={() => setGravatarEnabled(true)}
+              />
+              <label className="custom-control-label" htmlFor="radioGravatar">
+                <img src={GRAVATAR_DEFAULT} data-hide-in-vrt /> Gravatar
+              </label>
+              <a href="https://gravatar.com/">
+                <small><i className="icon-arrow-right-circle" aria-hidden="true"></i></small>
+              </a>
+            </div>
+          </h4>
+          <img src={generateGravatarSrc(currentUser.email)} width="64" data-hide-in-vrt />
+        </div>
+
+        <div className="col-md-6 col-12">
+          <h4>
+            <div className="custom-control custom-radio radio-primary">
+              <input
+                type="radio"
+                id="radioUploadPicture"
+                className="custom-control-input"
+                form="formImageType"
+                name="imagetypeForm[isGravatarEnabled]"
+                checked={!isGravatarEnabled}
+                onChange={() => setGravatarEnabled(false)}
+              />
+              <label className="custom-control-label" htmlFor="radioUploadPicture">
+                { t('Upload Image') }
+              </label>
+            </div>
+          </h4>
+          <div className="row mb-3">
+            <label className="col-sm-4 col-12 col-form-label text-left">
+              { t('Current Image') }
+            </label>
+            <div className="col-sm-8 col-12">
+              <p><img src={uploadedPictureSrc ?? DEFAULT_IMAGE} className="picture picture-lg rounded-circle" id="settingUserPicture" /></p>
+              {uploadedPictureSrc && <button type="button" className="btn btn-danger" onClick={deleteImageHandler}>{ t('Delete Image') }</button>}
+            </div>
+          </div>
+          <div className="row">
+            <label className="col-sm-4 col-12 col-form-label text-left">
+              {t('Upload new image')}
+            </label>
+            <div className="col-sm-8 col-12">
+              <input type="file" onChange={selectFileHandler} name="profileImage" accept="image/*" />
+            </div>
+          </div>
+        </div>
+      </div>
+
+      <ImageCropModal
+        show={showImageCropModal}
+        src={imageCropSrc}
+        onModalClose={() => setShowImageCropModal(false)}
+        onCropCompleted={cropCompletedHandler}
+      />
+
+      <div className="row my-3">
+        <div className="offset-4 col-5">
+          <button type="button" className="btn btn-primary" onClick={submit}>
+            {t('Update')}
+          </button>
+        </div>
+      </div>
+
+    </>
+  );
+
+};
+
+export default withUnstatedContainers(ProfileImageSettings, [AppContainer]);

+ 51 - 53
packages/app/src/components/Navbar/GrowiContextualSubNavigation.tsx

@@ -1,45 +1,41 @@
 import React, { useState, useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
-import PropTypes from 'prop-types';
-
 
+import PropTypes from 'prop-types';
+import { useTranslation } from 'react-i18next';
 import { DropdownItem } from 'reactstrap';
 
-import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
-import { IPageHasId, IPageToRenameWithMeta, IPageWithMeta } from '~/interfaces/page';
-
-import { withUnstatedContainers } from '../UnstatedUtils';
 import EditorContainer from '~/client/services/EditorContainer';
+import { exportAsMarkdown } from '~/client/services/page-operation';
+import { toastSuccess, toastError } from '~/client/util/apiNotification';
+import { apiPost } from '~/client/util/apiv1-client';
+import { IPageHasId, IPageToRenameWithMeta, IPageWithMeta } from '~/interfaces/page';
+import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
 import {
-  EditorMode, useDrawerMode, useEditorMode, useIsDeviceSmallerThanMd, useIsAbleToShowPageManagement, useIsAbleToShowTagLabel,
-  useIsAbleToShowPageEditorModeManager, useIsAbleToShowPageAuthors,
-} from '~/stores/ui';
+  useCurrentCreatedAt, useCurrentUpdatedAt, useCurrentPageId, useRevisionId, useCurrentPagePath,
+  useCreator, useRevisionAuthor, useCurrentUser, useIsGuestUser, useIsSharedUser, useShareLinkId,
+} from '~/stores/context';
 import {
   usePageAccessoriesModal, PageAccessoriesModalContents, IPageForPageDuplicateModal,
   usePageDuplicateModal, usePageRenameModal, usePageDeleteModal, usePagePresentationModal,
 } from '~/stores/modal';
-
-
-import {
-  useCurrentCreatedAt, useCurrentUpdatedAt, useCurrentPageId, useRevisionId, useCurrentPagePath,
-  useCreator, useRevisionAuthor, useCurrentUser, useIsGuestUser, useIsSharedUser, useShareLinkId,
-} from '~/stores/context';
 import { useSWRTagsInfo } from '~/stores/page';
+import {
+  EditorMode, useDrawerMode, useEditorMode, useIsDeviceSmallerThanMd, useIsAbleToShowPageManagement, useIsAbleToShowTagLabel,
+  useIsAbleToShowPageEditorModeManager, useIsAbleToShowPageAuthors,
+} from '~/stores/ui';
 
-
-import { toastSuccess, toastError } from '~/client/util/apiNotification';
-import { apiPost } from '~/client/util/apiv1-client';
-
-import HistoryIcon from '../Icons/HistoryIcon';
+import { AdditionalMenuItemsRendererProps } from '../Common/Dropdown/PageItemControl';
+import CreateTemplateModal from '../CreateTemplateModal';
 import AttachmentIcon from '../Icons/AttachmentIcon';
+import HistoryIcon from '../Icons/HistoryIcon';
+import PresentationIcon from '../Icons/PresentationIcon';
 import ShareLinkIcon from '../Icons/ShareLinkIcon';
-import { AdditionalMenuItemsRendererProps } from '../Common/Dropdown/PageItemControl';
-import { SubNavButtons } from './SubNavButtons';
-import PageEditorModeManager from './PageEditorModeManager';
+import { withUnstatedContainers } from '../UnstatedUtils';
+
+
 import { GrowiSubNavigation } from './GrowiSubNavigation';
-import PresentationIcon from '../Icons/PresentationIcon';
-import CreateTemplateModal from '../CreateTemplateModal';
-import { exportAsMarkdown } from '~/client/services/page-operation';
+import PageEditorModeManager from './PageEditorModeManager';
+import { SubNavButtons } from './SubNavButtons';
 
 
 type AdditionalMenuItemsProps = AdditionalMenuItemsRendererProps & {
@@ -101,6 +97,7 @@ const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
       <DropdownItem
         onClick={() => openAccessoriesModal(PageAccessoriesModalContents.PageHistory)}
         disabled={isGuestUser || isSharedUser}
+        data-testid="open-page-accessories-modal-btn-with-history-tab"
         className="grw-page-control-dropdown-item"
       >
         <span className="grw-page-control-dropdown-icon">
@@ -111,6 +108,7 @@ const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
 
       <DropdownItem
         onClick={() => openAccessoriesModal(PageAccessoriesModalContents.Attachment)}
+        data-testid="open-page-accessories-modal-btn-with-attachment-data-tab"
         className="grw-page-control-dropdown-item"
       >
         <span className="grw-page-control-dropdown-icon">
@@ -136,6 +134,7 @@ const AdditionalMenuItems = (props: AdditionalMenuItemsProps): JSX.Element => {
       <DropdownItem
         onClick={openPageTemplateModalHandler}
         className="grw-page-control-dropdown-item"
+        data-testid="open-page-template-modal-btn"
       >
         <i className="icon-fw icon-magic-wand grw-page-control-dropdown-icon"></i>
         { t('template.option_label.create/edit') }
@@ -246,36 +245,34 @@ const GrowiContextualSubNavigation = (props) => {
       mutateEditorMode(viewType);
     }
 
-    const className = `d-flex flex-column align-items-end justify-content-center ${isViewMode ? ' h-50' : ''}`;
-
     return (
       <>
-        <div className={className}>
+        <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
           { pageId != null && isViewMode && (
-            <SubNavButtons
-              isCompactMode={isCompactMode}
-              pageId={pageId}
-              shareLinkId={shareLinkId}
-              revisionId={revisionId}
-              path={path}
-              disableSeenUserInfoPopover={isSharedUser}
-              showPageControlDropdown={isAbleToShowPageManagement}
-              additionalMenuItemRenderer={props => (
-                <AdditionalMenuItems
-                  {...props}
-                  pageId={pageId}
-                  revisionId={revisionId}
-                  isLinkSharingDisabled={isLinkSharingDisabled}
-                  onClickTemplateMenuItem={templateMenuItemClickHandler}
-                />
-              )}
-              onClickDuplicateMenuItem={duplicateItemClickedHandler}
-              onClickRenameMenuItem={renameItemClickedHandler}
-              onClickDeleteMenuItem={deleteItemClickedHandler}
-            />
+            <div className="h-50">
+              <SubNavButtons
+                isCompactMode={isCompactMode}
+                pageId={pageId}
+                shareLinkId={shareLinkId}
+                revisionId={revisionId}
+                path={path}
+                disableSeenUserInfoPopover={isSharedUser}
+                showPageControlDropdown={isAbleToShowPageManagement}
+                additionalMenuItemRenderer={props => (
+                  <AdditionalMenuItems
+                    {...props}
+                    pageId={pageId}
+                    revisionId={revisionId}
+                    isLinkSharingDisabled={isLinkSharingDisabled}
+                    onClickTemplateMenuItem={templateMenuItemClickHandler}
+                  />
+                )}
+                onClickDuplicateMenuItem={duplicateItemClickedHandler}
+                onClickRenameMenuItem={renameItemClickedHandler}
+                onClickDeleteMenuItem={deleteItemClickedHandler}
+              />
+            </div>
           ) }
-        </div>
-        <div className={`${className} ${isCompactMode ? '' : 'mt-2'}`}>
           {isAbleToShowPageEditorModeManager && (
             <PageEditorModeManager
               onPageEditorModeButtonClicked={onPageEditorModeButtonClicked}
@@ -285,6 +282,7 @@ const GrowiContextualSubNavigation = (props) => {
             />
           )}
         </div>
+
         {currentUser != null && (
           <CreateTemplateModal
             path={path}

+ 9 - 10
packages/app/src/components/Navbar/GrowiNavbar.tsx

@@ -5,8 +5,9 @@ import { useTranslation } from 'react-i18next';
 import { UncontrolledTooltip } from 'reactstrap';
 
 import AppContainer from '~/client/services/AppContainer';
-import { IUser } from '~/interfaces/user';
-import { useIsSearchPage, useCurrentPagePath } from '~/stores/context';
+import {
+  useIsSearchPage, useCurrentPagePath, useIsGuestUser,
+} from '~/stores/context';
 import { usePageCreateModal } from '~/stores/modal';
 import { useIsDeviceSmallerThanMd } from '~/stores/ui';
 
@@ -19,16 +20,15 @@ import GlobalSearch from './GlobalSearch';
 import PersonalDropdown from './PersonalDropdown';
 
 
-type NavbarRightProps = {
-  currentUser: IUser,
-}
-const NavbarRight: FC<NavbarRightProps> = memo((props: NavbarRightProps) => {
+const NavbarRight = memo((): JSX.Element => {
   const { t } = useTranslation();
+
   const { data: currentPagePath } = useCurrentPagePath();
+  const { data: isGuestUser } = useIsGuestUser();
+
   const { open: openCreateModal } = usePageCreateModal();
 
-  const { currentUser } = props;
-  const isAuthenticated = currentUser != null;
+  const isAuthenticated = isGuestUser === false;
 
   const authenticatedNavItem = useMemo(() => {
     return (
@@ -110,7 +110,6 @@ const Confidential: FC<ConfidentialProps> = memo((props: ConfidentialProps) => {
 const GrowiNavbar = (props) => {
 
   const { appContainer } = props;
-  const { currentUser } = appContainer;
   const { crowi, isSearchServiceConfigured } = appContainer.config;
 
   const { data: isDeviceSmallerThanMd } = useIsDeviceSmallerThanMd();
@@ -132,7 +131,7 @@ const GrowiNavbar = (props) => {
 
       {/* Navbar Right  */}
       <ul className="navbar-nav ml-auto">
-        <NavbarRight currentUser={currentUser}></NavbarRight>
+        <NavbarRight></NavbarRight>
         <Confidential confidential={crowi.confidential}></Confidential>
       </ul>
 

+ 3 - 7
packages/app/src/components/Navbar/GrowiSubNavigation.tsx

@@ -1,19 +1,17 @@
 import React from 'react';
 
 import { IPageHasId } from '~/interfaces/page';
-
+import { IUser } from '~/interfaces/user';
 import {
   EditorMode, useEditorMode,
 } from '~/stores/ui';
 
 import TagLabels from '../Page/TagLabels';
+import PagePathNav from '../PagePathNav';
 
 import AuthorInfo from './AuthorInfo';
 import DrawerToggler from './DrawerToggler';
 
-import PagePathNav from '../PagePathNav';
-import { IUser } from '~/interfaces/user';
-
 
 type Props = {
   page: Partial<IPageHasId>,
@@ -85,9 +83,7 @@ export const GrowiSubNavigation = (props: Props): JSX.Element => {
       {/* Right side */}
       <div className="d-flex">
 
-        <div className="d-flex flex-column py-md-2" style={{ gap: `${isCompactMode ? '5px' : '0'}` }}>
-          { Controls && <Controls></Controls> }
-        </div>
+        { Controls && <Controls></Controls> }
 
         {/* Page Authors */}
         { (showPageAuthors && !isCompactMode) && (

+ 8 - 8
packages/app/src/components/Navbar/SubNavButtons.tsx

@@ -1,23 +1,22 @@
 import React, { useCallback } from 'react';
 
+import { toggleBookmark, toggleLike, toggleSubscribe } from '~/client/services/page-operation';
 import {
   IPageInfoAll, IPageToDeleteWithMeta, IPageToRenameWithMeta, isIPageInfoForEntity, isIPageInfoForOperation,
 } from '~/interfaces/page';
-
-import { useSWRxPageInfo } from '../../stores/page';
-import { useSWRBookmarkInfo } from '../../stores/bookmark';
-import { useSWRxUsersList } from '../../stores/user';
 import { useIsGuestUser } from '~/stores/context';
 import { IPageForPageDuplicateModal } from '~/stores/modal';
 
-import SubscribeButton from '../SubscribeButton';
-import LikeButtons from '../LikeButtons';
+import { useSWRBookmarkInfo } from '../../stores/bookmark';
+import { useSWRxPageInfo } from '../../stores/page';
+import { useSWRxUsersList } from '../../stores/user';
 import BookmarkButtons from '../BookmarkButtons';
-import SeenUserInfo from '../User/SeenUserInfo';
-import { toggleBookmark, toggleLike, toggleSubscribe } from '~/client/services/page-operation';
 import {
   AdditionalMenuItemsRendererProps, ForceHideMenuItems, MenuItemType, PageItemControl,
 } from '../Common/Dropdown/PageItemControl';
+import LikeButtons from '../LikeButtons';
+import SubscribeButton from '../SubscribeButton';
+import SeenUserInfo from '../User/SeenUserInfo';
 
 
 type CommonProps = {
@@ -184,6 +183,7 @@ const SubNavButtonsSubstance = (props: SubNavButtonsSubstanceProps): JSX.Element
       ) }
       { showPageControlDropdown && (
         <PageItemControl
+          alignRight
           pageId={pageId}
           pageInfo={pageInfo}
           isEnableActions={!isGuestUser}

+ 7 - 9
packages/app/src/components/NotAvailableForGuest.jsx

@@ -1,17 +1,16 @@
 import React from 'react';
-import PropTypes from 'prop-types';
 
+import PropTypes from 'prop-types';
 import { UncontrolledTooltip } from 'reactstrap';
 
-import AppContainer from '~/client/services/AppContainer';
-
-import { withUnstatedContainers } from './UnstatedUtils';
+import { useIsGuestUser } from '~/stores/context';
 
 const NotAvailableForGuest = (props) => {
-  const { appContainer, children } = props;
-  const isLoggedin = appContainer.currentUser != null;
+  const { children } = props;
+
+  const { data: isGuestUser } = useIsGuestUser();
 
-  if (isLoggedin) {
+  if (!isGuestUser) {
     return props.children;
   }
 
@@ -34,8 +33,7 @@ const NotAvailableForGuest = (props) => {
 };
 
 NotAvailableForGuest.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   children: PropTypes.node.isRequired,
 };
 
-export default withUnstatedContainers(NotAvailableForGuest, [AppContainer]);
+export default NotAvailableForGuest;

+ 37 - 9
packages/app/src/components/Page.jsx

@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useEffect, useRef } from 'react';
 
 import PropTypes from 'prop-types';
 
@@ -9,9 +9,9 @@ import EditorContainer from '~/client/services/EditorContainer';
 import PageContainer from '~/client/services/PageContainer';
 import { getOptionsToSave } from '~/client/util/editor';
 import {
-  useCurrentPagePath, useIsGuestUser, useSlackChannels,
+  useCurrentPagePath, useIsGuestUser,
 } from '~/stores/context';
-import { useIsSlackEnabled } from '~/stores/editor';
+import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
 import {
   useEditorMode, useIsMobile, useSelectedGrant, useSelectedGrantGroupId, useSelectedGrantGroupName,
 } from '~/stores/ui';
@@ -49,10 +49,6 @@ class Page extends React.Component {
     this.saveHandlerForDrawioModal = this.saveHandlerForDrawioModal.bind(this);
   }
 
-  componentWillMount() {
-    this.props.appContainer.registerComponentInstance('Page', this);
-  }
-
   /**
    * launch HandsontableModal with data specified by arguments
    * @param beginLineNumber
@@ -191,25 +187,57 @@ const PageWrapper = (props) => {
   const { data: editorMode } = useEditorMode();
   const { data: isGuestUser } = useIsGuestUser();
   const { data: isMobile } = useIsMobile();
+  const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
   const { data: isSlackEnabled } = useIsSlackEnabled();
-  const { data: slackChannels } = useSlackChannels();
   const { data: grant } = useSelectedGrant();
   const { data: grantGroupId } = useSelectedGrantGroupId();
   const { data: grantGroupName } = useSelectedGrantGroupName();
 
+  const pageRef = useRef(null);
+
+  // set handler to open DrawioModal
+  useEffect(() => {
+    const handler = (beginLineNumber, endLineNumber) => {
+      if (pageRef?.current != null) {
+        pageRef.current.launchDrawioModal(beginLineNumber, endLineNumber);
+      }
+    };
+    window.globalEmitter.on('launchDrawioModal', handler);
+
+    return function cleanup() {
+      window.globalEmitter.removeListener('launchDrawioModal', handler);
+    };
+  }, []);
+
+  // set handler to open HandsontableModal
+  useEffect(() => {
+    const handler = (beginLineNumber, endLineNumber) => {
+      if (pageRef?.current != null) {
+        pageRef.current.launchHandsontableModal(beginLineNumber, endLineNumber);
+      }
+    };
+    window.globalEmitter.on('launchHandsontableModal', handler);
+
+    return function cleanup() {
+      window.globalEmitter.removeListener('launchHandsontableModal', handler);
+    };
+  }, []);
+
   if (currentPagePath == null || editorMode == null || isGuestUser == null) {
     return null;
   }
 
+
   return (
     <Page
       {...props}
+      ref={pageRef}
       pagePath={currentPagePath}
       editorMode={editorMode}
       isGuestUser={isGuestUser}
       isMobile={isMobile}
       isSlackEnabled={isSlackEnabled}
-      slackChannels={slackChannels}
+      slackChannels={slackChannelsData.toString()}
       grant={grant}
       grantGroupId={grantGroupId}
       grantGroupName={grantGroupName}

+ 10 - 10
packages/app/src/components/Page/DisplaySwitcher.tsx

@@ -7,10 +7,10 @@ import { TabContent, TabPane } from 'reactstrap';
 
 import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
 import {
-  useCurrentPagePath, useIsSharedUser, useIsEditable, useCurrentPageId, useIsUserPage, usePageUser,
+  useCurrentPagePath, useIsSharedUser, useIsEditable, useCurrentPageId, useIsUserPage, usePageUser, useShareLinkId,
 } from '~/stores/context';
 import { useDescendantsPageListModal } from '~/stores/modal';
-import { useSWRxPageByPath } from '~/stores/page';
+import { useSWRxCurrentPage } from '~/stores/page';
 import { EditorMode, useEditorMode } from '~/stores/ui';
 
 import CountBadge from '../Common/CountBadge';
@@ -18,7 +18,7 @@ import ContentLinkButtons from '../ContentLinkButtons';
 import HashChanged from '../EventListeneres/HashChanged';
 import PageListIcon from '../Icons/PageListIcon';
 import Page from '../Page';
-import Editor from '../PageEditor';
+import PageEditor from '../PageEditor';
 import EditorNavbarBottom from '../PageEditor/EditorNavbarBottom';
 import PageEditorByHackmd from '../PageEditorByHackmd';
 import TableOfContents from '../TableOfContents';
@@ -33,18 +33,18 @@ const { isTopPage } = pagePathUtils;
 const DisplaySwitcher = (): JSX.Element => {
   const { t } = useTranslation();
 
-
   // get element for smoothScroll
   const getCommentListDom = useMemo(() => { return document.getElementById('page-comments-list') }, []);
 
 
   const { data: currentPageId } = useCurrentPageId();
-  const { data: currentPath } = useCurrentPagePath();
+  const { data: currentPagePath } = useCurrentPagePath();
   const { data: isSharedUser } = useIsSharedUser();
+  const { data: shareLinkId } = useShareLinkId();
   const { data: isUserPage } = useIsUserPage();
   const { data: isEditable } = useIsEditable();
   const { data: pageUser } = usePageUser();
-  const { data: currentPage } = useSWRxPageByPath(currentPath);
+  const { data: currentPage } = useSWRxCurrentPage(shareLinkId ?? undefined);
 
   const { data: editorMode } = useEditorMode();
 
@@ -52,7 +52,7 @@ const DisplaySwitcher = (): JSX.Element => {
 
   const isPageExist = currentPageId != null;
   const isViewMode = editorMode === EditorMode.View;
-  const isTopPagePath = isTopPage(currentPath ?? '');
+  const isTopPagePath = isTopPage(currentPagePath ?? '');
 
   return (
     <>
@@ -66,11 +66,11 @@ const DisplaySwitcher = (): JSX.Element => {
 
                   {/* Page list */}
                   <div className="grw-page-accessories-control">
-                    { currentPath != null && !isSharedUser && (
+                    { currentPagePath != null && !isSharedUser && (
                       <button
                         type="button"
                         className="btn btn-block btn-outline-secondary grw-btn-page-accessories rounded-pill d-flex justify-content-between align-items-center"
-                        onClick={() => openDescendantPageListModal(currentPath)}
+                        onClick={() => openDescendantPageListModal(currentPagePath)}
                       >
                         <div className="grw-page-accessories-control-icon">
                           <PageListIcon />
@@ -117,7 +117,7 @@ const DisplaySwitcher = (): JSX.Element => {
         { isEditable && (
           <TabPane tabId={EditorMode.Editor}>
             <div data-testid="page-editor" id="page-editor">
-              <Editor />
+              <PageEditor />
             </div>
           </TabPane>
         ) }

+ 0 - 72
packages/app/src/components/Page/NotFoundAlert.tsx

@@ -1,72 +0,0 @@
-import React, { useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
-import { UncontrolledTooltip } from 'reactstrap';
-import { useIsNotFoundPermalink } from '~/stores/context';
-
-import { EditorMode, useEditorMode } from '~/stores/ui';
-
-
-type Props = {
-  isGuestUserMode?: boolean,
-}
-
-const NotFoundAlert = (props: Props): JSX.Element => {
-  const { t } = useTranslation();
-  const { isGuestUserMode } = props;
-
-  const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
-  const { data: isNotFoundPermalink } = useIsNotFoundPermalink(); // TODO: Remove this when renaming on editor is implemented
-
-  const isEditorMode = editorMode !== EditorMode.View;
-
-  const clickHandler = useCallback(() => {
-    // check guest user,
-    // disabled of button cannot be used for using tooltip.
-    if (isGuestUserMode) {
-      return;
-    }
-
-    mutateEditorMode(EditorMode.Editor);
-
-  }, [isGuestUserMode, mutateEditorMode]);
-
-  if (isEditorMode) {
-    return <></>;
-  }
-
-  return (
-    <div className="border border-info p-3">
-      <div
-        className="col-md-12 p-0"
-      >
-        <h2 className="text-info lead">
-          <i className="icon-info pr-2 font-weight-bold" aria-hidden="true"></i>
-          {t('not_found_page.page_not_exist_alert')}
-        </h2>
-        {
-          !isNotFoundPermalink && (
-            <div id="create-page-btn-wrapper-for-tooltip" className="d-inline-block">
-              <button
-                type="button"
-                className={`pl-3 pr-3 btn bg-info text-white ${isGuestUserMode ? 'disabled' : ''}`}
-                onClick={clickHandler}
-              >
-                <i className="icon-note icon-fw" />
-                {t('not_found_page.Create Page')}
-              </button>
-            </div>
-          )
-        }
-
-        {!isNotFoundPermalink && isGuestUserMode && (
-          <UncontrolledTooltip placement="bottom" target="create-page-btn-wrapper-for-tooltip" fade={false}>
-            {t('Not available for guest')}
-          </UncontrolledTooltip>
-        )}
-      </div>
-    </div>
-  );
-};
-
-
-export default NotFoundAlert;

+ 3 - 8
packages/app/src/components/Page/RevisionBody.jsx

@@ -1,6 +1,6 @@
 import React from 'react';
-import PropTypes from 'prop-types';
 
+import PropTypes from 'prop-types';
 import { debounce } from 'throttle-debounce';
 
 export default class RevisionBody extends React.PureComponent {
@@ -58,12 +58,7 @@ export default class RevisionBody extends React.PureComponent {
     const additionalClassName = this.props.additionalClassName || '';
     return (
       <div
-        ref={(elm) => {
-          this.element = elm;
-          if (this.props.inputRef != null) {
-            this.props.inputRef(elm);
-          }
-        }}
+        ref={this.props.inputRef}
         id="wiki"
         className={`wiki ${additionalClassName}`}
         // eslint-disable-next-line react/no-danger
@@ -76,7 +71,7 @@ export default class RevisionBody extends React.PureComponent {
 
 RevisionBody.propTypes = {
   html: PropTypes.string,
-  inputRef: PropTypes.func, // for getting div element
+  inputRef: PropTypes.shape({ current: PropTypes.instanceOf(Element) }),
   isMathJaxEnabled: PropTypes.bool,
   renderMathJaxOnInit: PropTypes.bool,
   renderMathJaxInRealtime: PropTypes.bool,

+ 5 - 7
packages/app/src/components/Page/TrashPageAlert.jsx

@@ -1,18 +1,17 @@
 import React, { useState } from 'react';
-import PropTypes from 'prop-types';
 
-import { withTranslation } from 'react-i18next';
 
 import { UserPicture } from '@growi/ui';
-import { withUnstatedContainers } from '../UnstatedUtils';
-import AppContainer from '~/client/services/AppContainer';
-import PageContainer from '~/client/services/PageContainer';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
 
+import PageContainer from '~/client/services/PageContainer';
 import { useCurrentUpdatedAt, useShareLinkId } from '~/stores/context';
 import { usePageDeleteModal, usePutBackPageModal } from '~/stores/modal';
 import { useSWRxPageInfo } from '~/stores/page';
 
 import EmptyTrashModal from '../EmptyTrashModal';
+import { withUnstatedContainers } from '../UnstatedUtils';
 
 const onDeletedHandler = (pathOrPathsToDelete, isRecursively, isCompletely) => {
   if (typeof pathOrPathsToDelete !== 'string') {
@@ -145,12 +144,11 @@ const TrashPageAlert = (props) => {
 /**
  * Wrapper component for using unstated
  */
-const TrashPageAlertWrapper = withUnstatedContainers(TrashPageAlert, [AppContainer, PageContainer]);
+const TrashPageAlertWrapper = withUnstatedContainers(TrashPageAlert, [PageContainer]);
 
 
 TrashPageAlert.propTypes = {
   t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
 };
 

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

@@ -106,6 +106,7 @@ const PageAccessoriesModal = (props: Props): JSX.Element => {
       size="xl"
       isOpen={isOpened}
       toggle={close}
+      data-testid="page-accessories-modal"
       className={`grw-page-accessories-modal ${isWindowExpanded ? 'grw-modal-expanded' : ''} `}
     >
       <ModalHeader className="p-0" toggle={close} close={buttons}>

+ 30 - 18
packages/app/src/components/PageAttachment.jsx

@@ -2,12 +2,12 @@
 import React from 'react';
 
 import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
+import { useTranslation } from 'react-i18next';
 
-import AppContainer from '~/client/services/AppContainer';
 import PageContainer from '~/client/services/PageContainer';
 import { apiPost } from '~/client/util/apiv1-client';
 import { apiv3Get } from '~/client/util/apiv3-client';
+import { useIsGuestUser } from '~/stores/context';
 
 import DeleteAttachmentModal from './PageAttachment/DeleteAttachmentModal';
 import PageAttachmentList from './PageAttachment/PageAttachmentList';
@@ -110,19 +110,20 @@ class PageAttachment extends React.Component {
       });
   }
 
-  isUserLoggedIn() {
-    return this.props.appContainer.currentUser != null;
-  }
-
 
   render() {
-    const { t } = this.props;
+    const { t, isGuestUser } = this.props;
+
     if (this.state.attachments.length === 0) {
-      return t('No_attachments_yet');
+      return (
+        <div data-testid="page-attachment">
+          {t('No_attachments_yet')}
+        </div>
+      );
     }
 
     let deleteAttachmentModal = '';
-    if (this.isUserLoggedIn()) {
+    if (!isGuestUser) {
       const attachmentToDelete = this.state.attachmentToDelete;
       const deleteModalClose = () => {
         this.setState({ attachmentToDelete: null, deleteError: '' });
@@ -149,12 +150,12 @@ class PageAttachment extends React.Component {
     }
 
     return (
-      <>
+      <div data-testid="page-attachment">
         <PageAttachmentList
           attachments={this.state.attachments}
           inUse={this.state.inUse}
           onAttachmentDeleteClicked={this.onAttachmentDeleteClicked}
-          isUserLoggedIn={this.isUserLoggedIn()}
+          isUserLoggedIn={!isGuestUser}
         />
 
         {deleteAttachmentModal}
@@ -166,22 +167,33 @@ class PageAttachment extends React.Component {
           pagingLimit={this.state.limit}
           align="center"
         />
-      </>
+      </div>
     );
   }
 
 }
 
+PageAttachment.propTypes = {
+  t: PropTypes.func.isRequired,
+  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+
+  isGuestUser: PropTypes.bool.isRequired,
+};
+
 /**
  * Wrapper component for using unstated
  */
-const PageAttachmentWrapper = withUnstatedContainers(PageAttachment, [AppContainer, PageContainer]);
+const PageAttachmentUnstatedWrapper = withUnstatedContainers(PageAttachment, [PageContainer]);
 
+const PageAttachmentWrapper = (props) => {
+  const { t } = useTranslation();
+  const { data: isGuestUser } = useIsGuestUser();
 
-PageAttachment.propTypes = {
-  t: PropTypes.func.isRequired,
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+  if (isGuestUser == null) {
+    return <></>;
+  }
+
+  return <PageAttachmentUnstatedWrapper {...props} t={t} isGuestUser={isGuestUser} />;
 };
 
-export default withTranslation()(PageAttachmentWrapper);
+export default PageAttachmentWrapper;

+ 19 - 12
packages/app/src/components/PageComment/Comment.jsx

@@ -1,23 +1,24 @@
 import React from 'react';
-import PropTypes from 'prop-types';
 
-import { useTranslation } from 'react-i18next';
+import { UserPicture } from '@growi/ui';
 import { format } from 'date-fns';
-
+import PropTypes from 'prop-types';
+import { useTranslation } from 'react-i18next';
 import { UncontrolledTooltip } from 'reactstrap';
 
-import { UserPicture } from '@growi/ui';
 import AppContainer from '~/client/services/AppContainer';
 import PageContainer from '~/client/services/PageContainer';
-
-import { withUnstatedContainers } from '../UnstatedUtils';
+import { useCurrentUser } from '~/stores/context';
 
 import FormattedDistanceDate from '../FormattedDistanceDate';
+import HistoryIcon from '../Icons/HistoryIcon';
 import RevisionBody from '../Page/RevisionBody';
+import { withUnstatedContainers } from '../UnstatedUtils';
 import Username from '../User/Username';
-import CommentEditor from './CommentEditor';
+
 import CommentControl from './CommentControl';
-import HistoryIcon from '../Icons/HistoryIcon';
+import CommentEditor from './CommentEditor';
+
 
 /**
  *
@@ -74,11 +75,13 @@ class Comment extends React.PureComponent {
   }
 
   isCurrentUserEqualsToAuthor() {
-    const { creator } = this.props.comment;
-    if (creator == null) {
+    const { comment, currentUser } = this.props;
+    const { creator } = comment;
+
+    if (creator == null || currentUser == null) {
       return false;
     }
-    return creator.username === this.props.appContainer.currentUsername;
+    return creator.username === currentUser.username;
   }
 
   isCurrentRevision() {
@@ -235,12 +238,16 @@ Comment.propTypes = {
   isReadOnly: PropTypes.bool.isRequired,
   growiRenderer: PropTypes.object.isRequired,
   deleteBtnClicked: PropTypes.func.isRequired,
+  currentUser: PropTypes.object,
   onComment: PropTypes.func,
 };
 
 const CommentWrapperFC = (props) => {
   const { t } = useTranslation();
-  return <Comment t={t} {...props} />;
+
+  const { data: currentUser } = useCurrentUser();
+
+  return <Comment t={t} currentUser={currentUser} {...props} />;
 };
 
 /**

+ 31 - 10
packages/app/src/components/PageComment/CommentEditor.jsx

@@ -13,7 +13,8 @@ import CommentContainer from '~/client/services/CommentContainer';
 import EditorContainer from '~/client/services/EditorContainer';
 import PageContainer from '~/client/services/PageContainer';
 import GrowiRenderer from '~/client/util/GrowiRenderer';
-import { useCurrentUser } from '~/stores/context';
+import { useCurrentPagePath, useCurrentUser } from '~/stores/context';
+import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
 import { useIsMobile } from '~/stores/ui';
 
 import { CustomNavTab } from '../CustomNavigation/CustomNav';
@@ -64,6 +65,7 @@ class CommentEditor extends React.Component {
       isUploadableFile,
       errorMessage: undefined,
       isSlackConfigured: config.isSlackConfigured,
+      slackChannels: this.props.slackChannels,
     };
 
     this.updateState = this.updateState.bind(this);
@@ -77,8 +79,8 @@ class CommentEditor extends React.Component {
 
     this.renderHtml = this.renderHtml.bind(this);
     this.handleSelect = this.handleSelect.bind(this);
-    this.onSlackEnabledFlagChange = this.onSlackEnabledFlagChange.bind(this);
     this.onSlackChannelsChange = this.onSlackChannelsChange.bind(this);
+    this.fetchSlackChannels = this.fetchSlackChannels.bind(this);
   }
 
   updateState(value) {
@@ -97,12 +99,18 @@ class CommentEditor extends React.Component {
     this.renderHtml(this.state.comment);
   }
 
-  onSlackEnabledFlagChange(isSlackEnabled) {
-    this.props.commentContainer.setState({ isSlackEnabled });
+  fetchSlackChannels(slackChannels) {
+    this.setState({ slackChannels });
+  }
+
+  componentDidUpdate(prevProps) {
+    if (this.props.slackChannels !== prevProps.slackChannels) {
+      this.fetchSlackChannels(this.props.slackChannels);
+    }
   }
 
   onSlackChannelsChange(slackChannels) {
-    this.props.commentContainer.setState({ slackChannels });
+    this.setState({ slackChannels });
   }
 
   initializeEditor() {
@@ -165,8 +173,8 @@ class CommentEditor extends React.Component {
           this.state.comment,
           this.state.isMarkdown,
           replyTo,
-          commentContainer.state.isSlackEnabled,
-          commentContainer.state.slackChannels,
+          this.props.isSlackEnabled,
+          this.state.slackChannels,
         );
       }
       this.initializeEditor();
@@ -358,9 +366,9 @@ class CommentEditor extends React.Component {
               && (
                 <div className="form-inline align-self-center mr-md-2">
                   <SlackNotification
-                    isSlackEnabled={commentContainer.state.isSlackEnabled}
-                    slackChannels={commentContainer.state.slackChannels}
-                    onEnabledFlagChange={this.onSlackEnabledFlagChange}
+                    isSlackEnabled={this.props.isSlackEnabled}
+                    slackChannels={this.state.slackChannels}
+                    onEnabledFlagChange={this.props.onSlackEnabledFlagChange}
                     onChannelChange={this.onSlackChannelsChange}
                     id="idForComment"
                   />
@@ -416,6 +424,8 @@ CommentEditor.propTypes = {
   editorContainer: PropTypes.instanceOf(EditorContainer).isRequired,
   commentContainer: PropTypes.instanceOf(CommentContainer).isRequired,
 
+  slackChannels: PropTypes.string.isRequired,
+  isSlackEnabled: PropTypes.bool.isRequired,
   growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
   currentUser: PropTypes.instanceOf(Object),
   isMobile: PropTypes.bool,
@@ -426,15 +436,26 @@ CommentEditor.propTypes = {
   commentCreator: PropTypes.string,
   onCancelButtonClicked: PropTypes.func,
   onCommentButtonClicked: PropTypes.func,
+  onSlackEnabledFlagChange: PropTypes.func,
 };
 
 const CommentEditorWrapper = (props) => {
   const { data: isMobile } = useIsMobile();
   const { data: currentUser } = useCurrentUser();
+  const { data: isSlackEnabled, mutate: mutateIsSlackEnabled } = useIsSlackEnabled();
+  const { data: currentPagePath } = useCurrentPagePath();
+  const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
+
+  const onSlackEnabledFlagChange = (isSlackEnabled) => {
+    mutateIsSlackEnabled(isSlackEnabled, false);
+  };
 
   return (
     <CommentEditorHOCWrapper
       {...props}
+      onSlackEnabledFlagChange={onSlackEnabledFlagChange}
+      slackChannels={slackChannelsData.toString()}
+      isSlackEnabled={isSlackEnabled}
       currentUser={currentUser}
       isMobile={isMobile}
     />

+ 4 - 1
packages/app/src/components/PageCreateModal.jsx

@@ -12,6 +12,7 @@ import { debounce } from 'throttle-debounce';
 
 import AppContainer from '~/client/services/AppContainer';
 import { toastError } from '~/client/util/apiNotification';
+import { useCurrentUser } from '~/stores/context';
 import { usePageCreateModal } from '~/stores/modal';
 
 import PagePathAutoComplete from './PagePathAutoComplete';
@@ -25,13 +26,15 @@ const {
 const PageCreateModal = (props) => {
   const { t, appContainer } = props;
 
+  const { data: currentUser } = useCurrentUser();
+
   const { data: pageCreateModalData, close: closeCreateModal } = usePageCreateModal();
   const { isOpened, path } = pageCreateModalData;
 
   const config = appContainer.getConfig();
   const isReachable = config.isSearchServiceReachable;
   const pathname = path || '';
-  const userPageRootPath = userPageRoot(appContainer.currentUser);
+  const userPageRootPath = userPageRoot(currentUser);
   const isCreatable = isCreatablePage(pathname) || isUsersHomePage(pathname);
   const pageNameInputInitialValue = isCreatable ? pathUtils.addTrailingSlash(pathname) : '/';
   const now = format(new Date(), 'yyyy/MM/dd');

+ 0 - 440
packages/app/src/components/PageEditor.jsx

@@ -1,440 +0,0 @@
-import React from 'react';
-
-import { envUtils } from '@growi/core';
-import detectIndent from 'detect-indent';
-import PropTypes from 'prop-types';
-import { throttle, debounce } from 'throttle-debounce';
-
-import AppContainer from '~/client/services/AppContainer';
-import EditorContainer from '~/client/services/EditorContainer';
-import PageContainer from '~/client/services/PageContainer';
-import { apiGet, apiPost } from '~/client/util/apiv1-client';
-import { getOptionsToSave } from '~/client/util/editor';
-import { useIsEditable, useIsIndentSizeForced, useSlackChannels } from '~/stores/context';
-import { useCurrentIndentSize, useIsSlackEnabled, useIsTextlintEnabled } from '~/stores/editor';
-import {
-  useEditorMode, useIsMobile, useSelectedGrant, useSelectedGrantGroupId, useSelectedGrantGroupName,
-} from '~/stores/ui';
-import loggerFactory from '~/utils/logger';
-
-
-import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
-import Editor from './PageEditor/Editor';
-import Preview from './PageEditor/Preview';
-import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
-import { withUnstatedContainers } from './UnstatedUtils';
-
-
-// TODO: remove this when omitting unstated is completed
-
-const logger = loggerFactory('growi:PageEditor');
-
-class PageEditor extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.previewElement = React.createRef();
-
-    const config = this.props.appContainer.getConfig();
-    const isUploadable = config.upload.image || config.upload.file;
-    const isUploadableFile = config.upload.file;
-    const isMathJaxEnabled = !!config.env.MATHJAX;
-
-    this.state = {
-      markdown: this.props.pageContainer.state.markdown,
-      isUploadable,
-      isUploadableFile,
-      isMathJaxEnabled,
-    };
-
-    this.setCaretLine = this.setCaretLine.bind(this);
-    this.focusToEditor = this.focusToEditor.bind(this);
-    this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
-    this.onSaveWithShortcut = this.onSaveWithShortcut.bind(this);
-    this.onUpload = this.onUpload.bind(this);
-    this.onEditorScroll = this.onEditorScroll.bind(this);
-    this.onEditorScrollCursorIntoView = this.onEditorScrollCursorIntoView.bind(this);
-    this.onPreviewScroll = this.onPreviewScroll.bind(this);
-    this.saveDraft = this.saveDraft.bind(this);
-    this.clearDraft = this.clearDraft.bind(this);
-
-    // for scrolling
-    this.lastScrolledDateWithCursor = null;
-    this.isOriginOfScrollSyncEditor = false;
-    this.isOriginOfScrollSyncEditor = false;
-
-    // create throttled function
-    this.scrollPreviewByEditorLineWithThrottle = throttle(20, this.scrollPreviewByEditorLine);
-    this.scrollPreviewByCursorMovingWithThrottle = throttle(20, this.scrollPreviewByCursorMoving);
-    this.scrollEditorByPreviewScrollWithThrottle = throttle(20, this.scrollEditorByPreviewScroll);
-    this.setMarkdownStateWithDebounce = debounce(50, throttle(100, (value) => {
-      this.setState({ markdown: value });
-    }));
-    this.saveDraftWithDebounce = debounce(800, this.saveDraft);
-
-    // Detect indent size from contents (only when users are allowed to change it)
-    // TODO: https://youtrack.weseek.co.jp/issue/GW-5368
-    if (!props.isIndentSizeForced && this.state.markdown) {
-      const detectedIndent = detectIndent(this.state.markdown);
-      if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
-        props.mutateCurrentIndentSize(detectedIndent.amount);
-      }
-    }
-  }
-
-  componentWillMount() {
-    this.props.appContainer.registerComponentInstance('PageEditor', this);
-  }
-
-  getMarkdown() {
-    return this.state.markdown;
-  }
-
-  updateEditorValue(markdown) {
-    this.editor.setValue(markdown);
-  }
-
-  focusToEditor() {
-    this.editor.forceToFocus();
-  }
-
-  /**
-   * set caret position of editor
-   * @param {number} line
-   */
-  setCaretLine(line) {
-    this.editor.setCaretLine(line);
-    scrollSyncHelper.scrollPreview(this.previewElement, line);
-  }
-
-  /**
-   * the change event handler for `markdown` state
-   * @param {string} value
-   */
-  onMarkdownChanged(value) {
-    const { pageContainer } = this.props;
-    this.setMarkdownStateWithDebounce(value);
-    // only when the first time to edit
-    if (!pageContainer.state.revisionId) {
-      this.saveDraftWithDebounce();
-    }
-  }
-
-  // Displays an alert if there is a difference with pageContainer's markdown
-  componentDidUpdate(prevProps, prevState) {
-    const { pageContainer, editorContainer } = this.props;
-
-    if (this.state.markdown !== prevState.markdown) {
-      if (pageContainer.state.markdown !== this.state.markdown) {
-        editorContainer.enableUnsavedWarning();
-      }
-    }
-  }
-
-  /**
-   * save and update state of containers
-   */
-  async onSaveWithShortcut() {
-    const {
-      isSlackEnabled, slackChannels, grant, grantGroupId, grantGroupName, editorContainer, pageContainer,
-    } = this.props;
-
-    const optionsToSave = getOptionsToSave(isSlackEnabled, slackChannels, grant, grantGroupId, grantGroupName, editorContainer);
-
-    try {
-      // disable unsaved warning
-      editorContainer.disableUnsavedWarning();
-
-      // eslint-disable-next-line no-unused-vars
-      const { page, tags } = await pageContainer.save(this.state.markdown, this.props.editorMode, optionsToSave);
-      logger.debug('success to save');
-
-      pageContainer.showSuccessToastr();
-
-      // update state of EditorContainer
-      editorContainer.setState({ tags });
-    }
-    catch (error) {
-      logger.error('failed to save', error);
-      pageContainer.showErrorToastr(error);
-    }
-  }
-
-  /**
-   * the upload event handler
-   * @param {any} file
-   */
-  async onUpload(file) {
-    const {
-      appContainer, pageContainer, mutateGrant,
-    } = this.props;
-
-    try {
-      let res = await apiGet('/attachments.limit', {
-        fileSize: file.size,
-      });
-
-      if (!res.isUploadable) {
-        throw new Error(res.errorMessage);
-      }
-
-      const formData = new FormData();
-      const { pageId, path } = pageContainer.state;
-      formData.append('_csrf', appContainer.csrfToken);
-      formData.append('file', file);
-      formData.append('path', path);
-      if (pageId != null) {
-        formData.append('page_id', pageContainer.state.pageId);
-      }
-
-      res = await apiPost('/attachments.add', formData);
-      const attachment = res.attachment;
-      const fileName = attachment.originalName;
-
-      let insertText = `[${fileName}](${attachment.filePathProxied})`;
-      // when image
-      if (attachment.fileFormat.startsWith('image/')) {
-        // modify to "![fileName](url)" syntax
-        insertText = `!${insertText}`;
-      }
-      this.editor.insertText(insertText);
-
-      // when if created newly
-      if (res.pageCreated) {
-        logger.info('Page is created', res.page._id);
-        pageContainer.updateStateAfterSave(res.page, res.tags, res.revision, this.props.editorMode);
-        mutateGrant(res.page.grant);
-      }
-    }
-    catch (e) {
-      logger.error('failed to upload', e);
-      pageContainer.showErrorToastr(e);
-    }
-    finally {
-      this.editor.terminateUploadingState();
-    }
-  }
-
-  /**
-   * the scroll event handler from codemirror
-   * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
-   *                    the size of the scrollable area, and the size of the visible area (minus scrollbars).
-   *                    And data.line is also available that is added by Editor component
-   * @see https://codemirror.net/doc/manual.html#events
-   */
-  onEditorScroll(data) {
-    // prevent scrolling
-    //   if the elapsed time from last scroll with cursor is shorter than 40ms
-    const now = new Date();
-    if (now - this.lastScrolledDateWithCursor < 40) {
-      return;
-    }
-
-    this.scrollPreviewByEditorLineWithThrottle(data.line);
-  }
-
-  /**
-   * the scroll event handler from codemirror
-   * @param {number} line
-   * @see https://codemirror.net/doc/manual.html#events
-   */
-  onEditorScrollCursorIntoView(line) {
-    // record date
-    this.lastScrolledDateWithCursor = new Date();
-    this.scrollPreviewByCursorMovingWithThrottle(line);
-  }
-
-  /**
-   * scroll Preview element by scroll event
-   * @param {number} line
-   */
-  scrollPreviewByEditorLine(line) {
-    if (this.previewElement == null) {
-      return;
-    }
-
-    // prevent circular invocation
-    if (this.isOriginOfScrollSyncPreview) {
-      this.isOriginOfScrollSyncPreview = false; // turn off the flag
-      return;
-    }
-
-    // turn on the flag
-    this.isOriginOfScrollSyncEditor = true;
-    scrollSyncHelper.scrollPreview(this.previewElement, line);
-  }
-
-  /**
-   * scroll Preview element by cursor moving
-   * @param {number} line
-   */
-  scrollPreviewByCursorMoving(line) {
-    if (this.previewElement == null) {
-      return;
-    }
-
-    // prevent circular invocation
-    if (this.isOriginOfScrollSyncPreview) {
-      this.isOriginOfScrollSyncPreview = false; // turn off the flag
-      return;
-    }
-
-    // turn on the flag
-    this.isOriginOfScrollSyncEditor = true;
-    scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
-  }
-
-  /**
-   * the scroll event handler from Preview component
-   * @param {number} offset
-   */
-  onPreviewScroll(offset) {
-    this.scrollEditorByPreviewScrollWithThrottle(offset);
-  }
-
-  /**
-   * scroll Editor component by scroll event of Preview component
-   * @param {number} offset
-   */
-  scrollEditorByPreviewScroll(offset) {
-    if (this.previewElement == null) {
-      return;
-    }
-
-    // prevent circular invocation
-    if (this.isOriginOfScrollSyncEditor) {
-      this.isOriginOfScrollSyncEditor = false; // turn off the flag
-      return;
-    }
-
-    // turn on the flag
-    this.isOriginOfScrollSyncPreview = true;
-    scrollSyncHelper.scrollEditor(this.editor, this.previewElement, offset);
-  }
-
-  saveDraft() {
-    const { pageContainer, editorContainer } = this.props;
-    editorContainer.saveDraft(pageContainer.state.path, this.state.markdown);
-  }
-
-  clearDraft() {
-    this.props.editorContainer.clearDraft(this.props.pageContainer.state.path);
-  }
-
-  render() {
-    if (!this.props.isEditable) {
-      return null;
-    }
-
-    const config = this.props.appContainer.getConfig();
-    const noCdn = envUtils.toBoolean(config.env.NO_CDN);
-
-    return (
-      <div className="d-flex flex-wrap">
-        <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
-          <Editor
-            ref={(c) => { this.editor = c }}
-            value={this.state.markdown}
-            noCdn={noCdn}
-            isMobile={this.props.isMobile}
-            isUploadable={this.state.isUploadable}
-            isUploadableFile={this.state.isUploadableFile}
-            isTextlintEnabled={this.props.isTextlintEnabled}
-            indentSize={this.props.indentSize}
-            onScroll={this.onEditorScroll}
-            onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
-            onChange={this.onMarkdownChanged}
-            onUpload={this.onUpload}
-            onSave={this.onSaveWithShortcut}
-          />
-        </div>
-        <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
-          <Preview
-            markdown={this.state.markdown}
-            // eslint-disable-next-line no-return-assign
-            inputRef={(el) => { return this.previewElement = el }}
-            isMathJaxEnabled={this.state.isMathJaxEnabled}
-            renderMathJaxOnInit={false}
-            onScroll={this.onPreviewScroll}
-          />
-        </div>
-        <ConflictDiffModal
-          isOpen={this.props.pageContainer.state.isConflictDiffModalOpen}
-          onClose={() => this.props.pageContainer.setState({ isConflictDiffModalOpen: false })}
-          appContainer={this.props.appContainer}
-          pageContainer={this.props.pageContainer}
-          markdownOnEdit={this.state.markdown}
-        />
-      </div>
-    );
-  }
-
-}
-
-PageEditor.propTypes = {
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
-  editorContainer: PropTypes.instanceOf(EditorContainer).isRequired,
-
-  isEditable: PropTypes.bool.isRequired,
-
-  // TODO: remove this when omitting unstated is completed
-  editorMode: PropTypes.string.isRequired,
-  isMobile: PropTypes.bool,
-  isSlackEnabled: PropTypes.bool.isRequired,
-  slackChannels: PropTypes.string.isRequired,
-  grant: PropTypes.number.isRequired,
-  grantGroupId: PropTypes.string,
-  grantGroupName: PropTypes.string,
-  mutateGrant: PropTypes.func,
-  isTextlintEnabled: PropTypes.bool,
-  isIndentSizeForced: PropTypes.bool,
-  indentSize: PropTypes.number,
-  mutateCurrentIndentSize: PropTypes.func,
-};
-
-/**
- * Wrapper component for using unstated
- */
-const PageEditorHOCWrapper = withUnstatedContainers(PageEditor, [AppContainer, PageContainer, EditorContainer]);
-
-const PageEditorWrapper = (props) => {
-  const { data: isEditable } = useIsEditable();
-  const { data: editorMode } = useEditorMode();
-  const { data: isMobile } = useIsMobile();
-  const { data: isSlackEnabled } = useIsSlackEnabled();
-  const { data: slackChannels } = useSlackChannels();
-  const { data: grant, mutate: mutateGrant } = useSelectedGrant();
-  const { data: grantGroupId } = useSelectedGrantGroupId();
-  const { data: grantGroupName } = useSelectedGrantGroupName();
-  const { data: isTextlintEnabled } = useIsTextlintEnabled();
-  const { data: isIndentSizeForced } = useIsIndentSizeForced();
-  const { data: indentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
-
-  if (isEditable == null || editorMode == null) {
-    return null;
-  }
-
-  return (
-    <PageEditorHOCWrapper
-      {...props}
-      isEditable={isEditable}
-      editorMode={editorMode}
-      isMobile={isMobile}
-      isSlackEnabled={isSlackEnabled}
-      slackChannels={slackChannels}
-      grant={grant}
-      grantGroupId={grantGroupId}
-      grantGroupName={grantGroupName}
-      mutateGrant={mutateGrant}
-      isTextlintEnabled={isTextlintEnabled}
-      isIndentSizeForced={isIndentSizeForced}
-      indentSize={indentSize}
-      mutateCurrentIndentSize={mutateCurrentIndentSize}
-
-    />
-  );
-};
-
-export default PageEditorWrapper;

+ 435 - 0
packages/app/src/components/PageEditor.tsx

@@ -0,0 +1,435 @@
+import React, {
+  useCallback, useEffect, useMemo, useRef, useState,
+} from 'react';
+
+import EventEmitter from 'events';
+
+import { envUtils } from '@growi/core';
+import detectIndent from 'detect-indent';
+import { throttle, debounce } from 'throttle-debounce';
+
+import AppContainer from '~/client/services/AppContainer';
+import EditorContainer from '~/client/services/EditorContainer';
+import PageContainer from '~/client/services/PageContainer';
+import { apiGet, apiPost } from '~/client/util/apiv1-client';
+import { getOptionsToSave } from '~/client/util/editor';
+import { useIsEditable, useIsIndentSizeForced, useCurrentPagePath } from '~/stores/context';
+import {
+  useCurrentIndentSize, useSWRxSlackChannels, useIsSlackEnabled, useIsTextlintEnabled,
+} from '~/stores/editor';
+import {
+  EditorMode,
+  useEditorMode, useIsMobile, useSelectedGrant, useSelectedGrantGroupId, useSelectedGrantGroupName,
+} from '~/stores/ui';
+import loggerFactory from '~/utils/logger';
+
+
+import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
+import Editor from './PageEditor/Editor';
+import Preview from './PageEditor/Preview';
+import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
+import { withUnstatedContainers } from './UnstatedUtils';
+
+
+// TODO: remove this when omitting unstated is completed
+
+const logger = loggerFactory('growi:PageEditor');
+
+
+declare let window: {
+  globalEmitter: EventEmitter,
+};
+
+type EditorRef = {
+  setValue: (markdown: string) => void,
+  setCaretLine: (line: number) => void,
+  insertText: (text: string) => void,
+  forceToFocus: () => void,
+  terminateUploadingState: () => void,
+}
+
+type Props = {
+  appContainer: AppContainer,
+  pageContainer: PageContainer,
+  editorContainer: EditorContainer,
+
+  isEditable: boolean,
+
+  editorMode: string,
+  isSlackEnabled: boolean,
+  slackChannels: string,
+  isMobile?: boolean,
+
+  grant: number,
+  grantGroupId?: string,
+  grantGroupName?: string,
+  mutateGrant: (grant: number) => void,
+
+  isTextlintEnabled?: boolean,
+  isIndentSizeForced?: boolean,
+  indentSize?: number,
+  mutateCurrentIndentSize: (indent: number) => void,
+};
+
+// for scrolling
+let lastScrolledDateWithCursor: Date | null = null;
+let isOriginOfScrollSyncEditor = false;
+let isOriginOfScrollSyncPreview = false;
+
+const PageEditor = (props: Props): JSX.Element => {
+  const {
+    appContainer, pageContainer, editorContainer,
+  } = props;
+
+  const { data: isEditable } = useIsEditable();
+  const { data: editorMode } = useEditorMode();
+  const { data: isMobile } = useIsMobile();
+  const { data: isSlackEnabled } = useIsSlackEnabled();
+  const { data: currentPagePath } = useCurrentPagePath();
+  const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
+  const { data: grant, mutate: mutateGrant } = useSelectedGrant();
+  const { data: grantGroupId } = useSelectedGrantGroupId();
+  const { data: grantGroupName } = useSelectedGrantGroupName();
+  const { data: isTextlintEnabled } = useIsTextlintEnabled();
+  const { data: isIndentSizeForced } = useIsIndentSizeForced();
+  const { data: indentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
+
+  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+  const [markdown, setMarkdown] = useState<string>(pageContainer.state.markdown!);
+
+
+  const editorRef = useRef<EditorRef>(null);
+  const previewRef = useRef<HTMLDivElement>(null);
+
+  const setMarkdownWithDebounce = useMemo(() => debounce(50, throttle(100, value => setMarkdown(value))), []);
+  const saveDraftWithDebounce = useMemo(() => debounce(800, () => {
+    editorContainer.saveDraft(pageContainer.state.path, markdown);
+  }), [editorContainer, markdown, pageContainer.state.path]);
+
+  const markdownChangedHandler = useCallback((value: string): void => {
+    setMarkdownWithDebounce(value);
+    // only when the first time to edit
+    if (!pageContainer.state.revisionId) {
+      saveDraftWithDebounce();
+    }
+  }, [pageContainer.state.revisionId, saveDraftWithDebounce, setMarkdownWithDebounce]);
+
+
+  const saveWithShortcut = useCallback(async() => {
+    if (grant == null) {
+      return;
+    }
+
+    const slackChannels = slackChannelsData ? slackChannelsData.toString() : '';
+
+    const optionsToSave = getOptionsToSave(isSlackEnabled ?? false, slackChannels, grant, grantGroupId, grantGroupName, editorContainer);
+
+    try {
+      // disable unsaved warning
+      editorContainer.disableUnsavedWarning();
+
+      // eslint-disable-next-line no-unused-vars
+      const { tags } = await pageContainer.save(markdown, editorMode, optionsToSave);
+      logger.debug('success to save');
+
+      pageContainer.showSuccessToastr();
+
+      // update state of EditorContainer
+      editorContainer.setState({ tags });
+    }
+    catch (error) {
+      logger.error('failed to save', error);
+      pageContainer.showErrorToastr(error);
+    }
+  }, [editorContainer, editorMode, grant, grantGroupId, grantGroupName, isSlackEnabled, slackChannelsData, markdown, pageContainer]);
+
+
+  /**
+   * the upload event handler
+   * @param {any} file
+   */
+  const uploadHandler = useCallback(async(file) => {
+    if (editorRef.current == null) {
+      return;
+    }
+
+    try {
+      // eslint-disable-next-line @typescript-eslint/no-explicit-any
+      let res: any = await apiGet('/attachments.limit', {
+        fileSize: file.size,
+      });
+
+      if (!res.isUploadable) {
+        throw new Error(res.errorMessage);
+      }
+
+      const formData = new FormData();
+      const { pageId, path } = pageContainer.state;
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      formData.append('_csrf', appContainer.csrfToken!);
+      formData.append('file', file);
+      if (path != null) {
+        formData.append('path', path);
+      }
+      if (pageId != null) {
+        formData.append('page_id', pageId);
+      }
+
+      res = await apiPost('/attachments.add', formData);
+      const attachment = res.attachment;
+      const fileName = attachment.originalName;
+
+      let insertText = `[${fileName}](${attachment.filePathProxied})`;
+      // when image
+      if (attachment.fileFormat.startsWith('image/')) {
+        // modify to "![fileName](url)" syntax
+        insertText = `!${insertText}`;
+      }
+      editorRef.current.insertText(insertText);
+
+      // when if created newly
+      if (res.pageCreated) {
+        logger.info('Page is created', res.page._id);
+        pageContainer.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
+        mutateGrant(res.page.grant);
+      }
+    }
+    catch (e) {
+      logger.error('failed to upload', e);
+      pageContainer.showErrorToastr(e);
+    }
+    finally {
+      editorRef.current.terminateUploadingState();
+    }
+  }, [appContainer.csrfToken, editorMode, mutateGrant, pageContainer]);
+
+
+  const scrollPreviewByEditorLine = useCallback((line: number) => {
+    if (previewRef.current == null) {
+      return;
+    }
+
+    // prevent circular invocation
+    if (isOriginOfScrollSyncPreview) {
+      isOriginOfScrollSyncPreview = false; // turn off the flag
+      return;
+    }
+
+    // turn on the flag
+    isOriginOfScrollSyncEditor = true;
+    scrollSyncHelper.scrollPreview(previewRef.current, line);
+  }, []);
+  const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
+
+  /**
+   * the scroll event handler from codemirror
+   * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
+   *                    the size of the scrollable area, and the size of the visible area (minus scrollbars).
+   *                    And data.line is also available that is added by Editor component
+   * @see https://codemirror.net/doc/manual.html#events
+   */
+  const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
+    // prevent scrolling
+    //   if the elapsed time from last scroll with cursor is shorter than 40ms
+    const now = new Date();
+    if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
+      return;
+    }
+
+    scrollPreviewByEditorLineWithThrottle(line);
+  }, [scrollPreviewByEditorLineWithThrottle]);
+
+  /**
+   * scroll Preview element by cursor moving
+   * @param {number} line
+   */
+  const scrollPreviewByCursorMoving = useCallback((line: number) => {
+    if (previewRef.current == null) {
+      return;
+    }
+
+    // prevent circular invocation
+    if (isOriginOfScrollSyncPreview) {
+      isOriginOfScrollSyncPreview = false; // turn off the flag
+      return;
+    }
+
+    // turn on the flag
+    isOriginOfScrollSyncEditor = true;
+    scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
+  }, []);
+  const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
+
+  /**
+   * the scroll event handler from codemirror
+   * @param {number} line
+   * @see https://codemirror.net/doc/manual.html#events
+   */
+  const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
+    // record date
+    lastScrolledDateWithCursor = new Date();
+    scrollPreviewByCursorMovingWithThrottle(line);
+  }, [scrollPreviewByCursorMovingWithThrottle]);
+
+  /**
+   * scroll Editor component by scroll event of Preview component
+   * @param {number} offset
+   */
+  const scrollEditorByPreviewScroll = useCallback((offset: number) => {
+    if (editorRef.current == null || previewRef.current == null) {
+      return;
+    }
+
+    // prevent circular invocation
+    if (isOriginOfScrollSyncEditor) {
+      isOriginOfScrollSyncEditor = false; // turn off the flag
+      return;
+    }
+
+    // turn on the flag
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    isOriginOfScrollSyncPreview = true;
+
+    scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
+  }, []);
+  const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
+
+
+  // register dummy instance to get markdown
+  useEffect(() => {
+    const pageEditorInstance = {
+      getMarkdown: () => {
+        return markdown;
+      },
+    };
+    appContainer.registerComponentInstance('PageEditor', pageEditorInstance);
+  }, [appContainer, markdown]);
+
+  // initial caret line
+  useEffect(() => {
+    if (editorRef.current != null) {
+      editorRef.current.setCaretLine(0);
+    }
+  }, []);
+
+  // set handler to set caret line
+  useEffect(() => {
+    const handler = (line) => {
+      if (editorRef.current != null) {
+        editorRef.current.setCaretLine(line);
+      }
+      if (previewRef.current != null) {
+        scrollSyncHelper.scrollPreview(previewRef.current, line);
+      }
+    };
+    window.globalEmitter.on('setCaretLine', handler);
+
+    return function cleanup() {
+      window.globalEmitter.removeListener('setCaretLine', handler);
+    };
+  }, []);
+
+  // set handler to focus
+  useEffect(() => {
+    if (editorRef.current != null && editorMode === EditorMode.Editor) {
+      editorRef.current.forceToFocus();
+    }
+  }, [editorMode]);
+
+  // set handler to update editor value
+  useEffect(() => {
+    const handler = (markdown) => {
+      if (editorRef.current != null) {
+        editorRef.current.setValue(markdown);
+      }
+    };
+    window.globalEmitter.on('updateEditorValue', handler);
+
+    return function cleanup() {
+      window.globalEmitter.removeListener('updateEditorValue', handler);
+    };
+  }, []);
+
+  // Displays an alert if there is a difference with pageContainer's markdown
+  useEffect(() => {
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    if (pageContainer.state.markdown! !== markdown) {
+      editorContainer.enableUnsavedWarning();
+    }
+  }, [editorContainer, markdown, pageContainer.state.markdown]);
+
+  // Detect indent size from contents (only when users are allowed to change it)
+  useEffect(() => {
+    const currentPageMarkdown = pageContainer.state.markdown;
+    if (!isIndentSizeForced && currentPageMarkdown != null) {
+      const detectedIndent = detectIndent(currentPageMarkdown);
+      if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
+        mutateCurrentIndentSize(detectedIndent.amount);
+      }
+    }
+  }, [isIndentSizeForced, mutateCurrentIndentSize, pageContainer.state.markdown]);
+
+
+  if (!isEditable) {
+    return <></>;
+  }
+
+  const config = props.appContainer.getConfig();
+  const isUploadable = config.upload.image || config.upload.file;
+  const isUploadableFile = config.upload.file;
+  const isMathJaxEnabled = !!config.env.MATHJAX;
+
+  const noCdn = envUtils.toBoolean(config.env.NO_CDN);
+
+  // TODO: omit no-explicit-any -- 2022.06.02 Yuki Takei
+  // It is impossible to avoid the error
+  //  "Property '...' does not exist on type 'IntrinsicAttributes & RefAttributes<any>'"
+  //  because Editor is a class component and must be wrapped with React.forwardRef
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  const EditorAny = Editor as any;
+
+  return (
+    <div className="d-flex flex-wrap">
+      <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
+        <EditorAny
+          ref={editorRef}
+          value={markdown}
+          noCdn={noCdn}
+          isMobile={isMobile}
+          isUploadable={isUploadable}
+          isUploadableFile={isUploadableFile}
+          isTextlintEnabled={isTextlintEnabled}
+          indentSize={indentSize}
+          onScroll={editorScrolledHandler}
+          onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
+          onChange={markdownChangedHandler}
+          onUpload={uploadHandler}
+          onSave={() => saveWithShortcut()}
+        />
+      </div>
+      <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
+        <Preview
+          markdown={markdown}
+          // eslint-disable-next-line no-return-assign
+          inputRef={previewRef}
+          isMathJaxEnabled={isMathJaxEnabled}
+          renderMathJaxOnInit={false}
+          onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
+        />
+      </div>
+      <ConflictDiffModal
+        isOpen={pageContainer.state.isConflictDiffModalOpen}
+        onClose={() => pageContainer.setState({ isConflictDiffModalOpen: false })}
+        pageContainer={pageContainer}
+        markdownOnEdit={markdown}
+      />
+    </div>
+  );
+};
+
+/**
+   * Wrapper component for using unstated
+   */
+const PageEditorWrapper = withUnstatedContainers(PageEditor, [AppContainer, PageContainer, EditorContainer]);
+
+export default PageEditorWrapper;

+ 42 - 49
packages/app/src/components/PageEditor/ConflictDiffModal.tsx

@@ -1,22 +1,22 @@
 import React, {
-  useState, useEffect, FC, useRef,
+  useState, useEffect, useRef, useMemo, useCallback,
 } from 'react';
-import PropTypes from 'prop-types';
+
 import { UserPicture } from '@growi/ui';
+import CodeMirror from 'codemirror/lib/codemirror';
+import { format } from 'date-fns';
+import { useTranslation } from 'react-i18next';
 import {
   Modal, ModalHeader, ModalBody, ModalFooter,
 } from 'reactstrap';
-import { useTranslation } from 'react-i18next';
-import { format } from 'date-fns';
-import CodeMirror from 'codemirror/lib/codemirror';
-
-import PageContainer from '../../client/services/PageContainer';
-import AppContainer from '../../client/services/AppContainer';
-import ExpandOrContractButton from '../ExpandOrContractButton';
 
+import { IUser } from '~/interfaces/user';
+import { useCurrentUser } from '~/stores/context';
 import { useEditorMode } from '~/stores/ui';
 
+import PageContainer from '../../client/services/PageContainer';
 import { IRevisionOnConflict } from '../../interfaces/revision';
+import ExpandOrContractButton from '../ExpandOrContractButton';
 import { UncontrolledCodeMirror } from '../UncontrolledCodeMirror';
 
 require('codemirror/lib/codemirror.css');
@@ -27,10 +27,9 @@ const DMP = require('diff_match_patch');
 Object.keys(DMP).forEach((key) => { window[key] = DMP[key] });
 
 type ConflictDiffModalProps = {
-  isOpen: boolean | null;
+  isOpen?: boolean;
   onClose?: (() => void);
   pageContainer: PageContainer;
-  appContainer: AppContainer;
   markdownOnEdit: string;
 };
 
@@ -38,26 +37,26 @@ type IRevisionOnConflictWithStringDate = Omit<IRevisionOnConflict, 'createdAt'>
   createdAt: string
 }
 
-export const ConflictDiffModal: FC<ConflictDiffModalProps> = (props) => {
+const ConflictDiffModalCore = (props: ConflictDiffModalProps & { currentUser: IUser }): JSX.Element => {
+  const { currentUser, pageContainer, onClose } = props;
+
+  const { data: editorMode } = useEditorMode();
+
   const { t } = useTranslation('');
   const [resolvedRevision, setResolvedRevision] = useState<string>('');
   const [isRevisionselected, setIsRevisionSelected] = useState<boolean>(false);
   const [isModalExpanded, setIsModalExpanded] = useState<boolean>(false);
   const [codeMirrorRef, setCodeMirrorRef] = useState<HTMLDivElement | null>(null);
 
-  const { data: editorMode } = useEditorMode();
-
   const uncontrolledRef = useRef<CodeMirror>(null);
 
-  const { pageContainer, appContainer } = props;
-
   const currentTime: Date = new Date();
 
   const request: IRevisionOnConflictWithStringDate = {
     revisionId: '',
     revisionBody: props.markdownOnEdit,
     createdAt: format(currentTime, 'yyyy/MM/dd HH:mm:ss'),
-    user: appContainer.currentUser,
+    user: currentUser,
   };
   const origin: IRevisionOnConflictWithStringDate = {
     revisionId: pageContainer.state.revisionId || '',
@@ -89,13 +88,13 @@ export const ConflictDiffModal: FC<ConflictDiffModalProps> = (props) => {
     }
   }, [codeMirrorRef, origin.revisionBody, request.revisionBody, latest.revisionBody]);
 
-  const onClose = () => {
-    if (props.onClose != null) {
-      props.onClose();
+  const close = useCallback(() => {
+    if (onClose != null) {
+      onClose();
     }
-  };
+  }, [onClose]);
 
-  const onResolveConflict = async() : Promise<void> => {
+  const onResolveConflict = useCallback(async() => {
     // disable button after clicked
     setIsRevisionSelected(false);
 
@@ -103,40 +102,34 @@ export const ConflictDiffModal: FC<ConflictDiffModalProps> = (props) => {
 
     try {
       await pageContainer.resolveConflict(codeMirrorVal, editorMode);
-      onClose();
+      close();
       pageContainer.showSuccessToastr();
     }
     catch (error) {
       pageContainer.showErrorToastr(error);
     }
 
-  };
-
-  const onExpandModal = () => {
-    setIsModalExpanded(true);
-  };
+  }, [editorMode, close, pageContainer]);
 
-  const onContractModal = () => {
-    setIsModalExpanded(false);
-  };
-
-  const resizeAndCloseButtons = (
+  const resizeAndCloseButtons = useMemo(() => (
     <div className="d-flex flex-nowrap">
       <ExpandOrContractButton
         isWindowExpanded={isModalExpanded}
-        expandWindow={onExpandModal}
-        contractWindow={onContractModal}
+        expandWindow={() => setIsModalExpanded(true)}
+        contractWindow={() => setIsModalExpanded(false)}
       />
-      <button type="button" className="close text-white" onClick={onClose} aria-label="Close">
+      <button type="button" className="close text-white" onClick={close} aria-label="Close">
         <span aria-hidden="true">&times;</span>
       </button>
     </div>
-  );
+  ), [isModalExpanded, close]);
+
+  const isOpen = props.isOpen ?? false;
 
   return (
     <Modal
-      isOpen={props.isOpen || false}
-      toggle={onClose}
+      isOpen={isOpen}
+      toggle={close}
       backdrop="static"
       className={`${isModalExpanded ? ' grw-modal-expanded' : ''}`}
       size="xl"
@@ -145,7 +138,7 @@ export const ConflictDiffModal: FC<ConflictDiffModalProps> = (props) => {
         <i className="icon-fw icon-exclamation" />{t('modal_resolve_conflict.resolve_conflict')}
       </ModalHeader>
       <ModalBody className="mx-4 my-1">
-        { props.isOpen
+        { isOpen
         && (
           <div className="row">
             <div className="col-12 text-center mt-2 mb-4">
@@ -269,14 +262,14 @@ export const ConflictDiffModal: FC<ConflictDiffModalProps> = (props) => {
   );
 };
 
-ConflictDiffModal.propTypes = {
-  isOpen: PropTypes.bool,
-  onClose: PropTypes.func,
-  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  markdownOnEdit: PropTypes.string.isRequired,
-};
 
-ConflictDiffModal.defaultProps = {
-  isOpen: false,
+export const ConflictDiffModal = (props: ConflictDiffModalProps): JSX.Element => {
+  const { isOpen } = props;
+  const { data: currentUser } = useCurrentUser();
+
+  if (!isOpen || currentUser == null) {
+    return <></>;
+  }
+
+  return <ConflictDiffModalCore {...props} currentUser={currentUser} />;
 };

+ 49 - 30
packages/app/src/components/PageEditor/EditorNavbarBottom.tsx

@@ -1,23 +1,24 @@
-import React, { useCallback, useState } from 'react';
-import PropTypes from 'prop-types';
+import React, { useCallback, useState, useEffect } from 'react';
 
+import PropTypes from 'prop-types';
 import { Collapse, Button } from 'reactstrap';
 
-import EditorContainer from '~/client/services/EditorContainer';
+
 import AppContainer from '~/client/services/AppContainer';
+import EditorContainer from '~/client/services/EditorContainer';
+import { useCurrentPagePath } from '~/stores/context';
+import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
 import {
   EditorMode, useDrawerOpened, useEditorMode, useIsDeviceSmallerThanMd,
 } from '~/stores/ui';
 
-import { SlackNotification } from '../SlackNotification';
+import SavePageControls from '../SavePageControls';
 import SlackLogo from '../SlackLogo';
+import { SlackNotification } from '../SlackNotification';
 import { withUnstatedContainers } from '../UnstatedUtils';
 
-import SavePageControls from '../SavePageControls';
 
 import OptionsSelector from './OptionsSelector';
-import { useIsSlackEnabled } from '~/stores/editor';
-import { useSlackChannels } from '~/stores/context';
 
 const EditorNavbarBottom = (props) => {
 
@@ -30,17 +31,28 @@ const EditorNavbarBottom = (props) => {
 
   const { mutate: mutateDrawerOpened } = useDrawerOpened();
   const { data: isDeviceSmallerThanMd } = useIsDeviceSmallerThanMd();
-  const { data: isSlackEnabled, mutate: mutateIsSlackEnabled } = useIsSlackEnabled();
-  const { data: slackChannels, mutate: mutateSlackChannels } = useSlackChannels();
   const additionalClasses = ['grw-editor-navbar-bottom'];
+  const { data: currentPagePath } = useCurrentPagePath();
+  const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
+  const { data: isSlackEnabled, mutate: mutateIsSlackEnabled } = useIsSlackEnabled();
 
-  const isSlackEnabledToggleHandler = useCallback(
-    (bool: boolean) => mutateIsSlackEnabled(bool), [mutateIsSlackEnabled],
-  );
+  const [slackChannelsStr, setSlackChannelsStr] = useState<string>('');
+
+  useEffect(() => {
+    if (slackChannelsData != null) {
+      setSlackChannelsStr(slackChannelsData.toString());
+      mutateIsSlackEnabled(false);
+    }
+  }, [mutateIsSlackEnabled, slackChannelsData]);
+
+  const isSlackEnabledToggleHandler = (bool: boolean) => {
+    mutateIsSlackEnabled(bool, false);
+  };
+
+  const slackChannelsChangedHandler = useCallback((slackChannels: string) => {
+    setSlackChannelsStr(slackChannels);
+  }, []);
 
-  const slackChannelsChangedHandler = useCallback(
-    (slackChannels: string) => mutateSlackChannels(slackChannels), [mutateSlackChannels],
-  );
 
   const renderDrawerButton = () => (
     <button
@@ -73,13 +85,17 @@ const EditorNavbarBottom = (props) => {
       {isSlackConfigured && (
         <Collapse isOpen={isSlackExpanded && isDeviceSmallerThanMd === true}>
           <nav className={`navbar navbar-expand-lg border-top ${additionalClasses.join(' ')}`}>
-            <SlackNotification
-              isSlackEnabled={isSlackEnabled ?? false}
-              slackChannels={slackChannels}
-              onEnabledFlagChange={isSlackEnabledToggleHandler}
-              onChannelChange={slackChannelsChangedHandler}
-              id="idForEditorNavbarBottomForMobile"
-            />
+            {isSlackEnabled != null
+            && (
+              <SlackNotification
+                isSlackEnabled={isSlackEnabled}
+                slackChannels={slackChannelsStr}
+                onEnabledFlagChange={isSlackEnabledToggleHandler}
+                onChannelChange={slackChannelsChangedHandler}
+                id="idForEditorNavbarBottomForMobile"
+              />
+            )
+            }
           </nav>
         </Collapse>
       )
@@ -104,16 +120,19 @@ const EditorNavbarBottom = (props) => {
             </Button>
           ) : (
             <div className="mr-2">
-              <SlackNotification
-                isSlackEnabled={isSlackEnabled ?? false}
-                slackChannels={slackChannels}
-                onEnabledFlagChange={isSlackEnabledToggleHandler}
-                onChannelChange={slackChannelsChangedHandler}
-                id="idForEditorNavbarBottom"
-              />
+              {isSlackEnabled != null
+              && (
+                <SlackNotification
+                  isSlackEnabled={isSlackEnabled}
+                  slackChannels={slackChannelsStr}
+                  onEnabledFlagChange={isSlackEnabledToggleHandler}
+                  onChannelChange={slackChannelsChangedHandler}
+                  id="idForEditorNavbarBottom"
+                />
+              )}
             </div>
           ))}
-          <SavePageControls />
+          <SavePageControls slackChannels={slackChannelsStr} isSlackEnabled={isSlackEnabled || false} />
           { isCollapsedOptionsSelectorEnabled && renderExpandButton() }
         </form>
       </div>

+ 13 - 5
packages/app/src/components/PageEditor/Preview.tsx

@@ -1,5 +1,5 @@
 import React, {
-  UIEventHandler, useCallback, useEffect, useMemo, useState,
+  useCallback, useEffect, useMemo, useState, SyntheticEvent,
 } from 'react';
 
 
@@ -18,7 +18,7 @@ type Props = {
   inputRef?: React.RefObject<HTMLDivElement>,
   isMathJaxEnabled?: boolean,
   renderMathJaxOnInit?: boolean,
-  onScroll?: UIEventHandler<HTMLDivElement>,
+  onScroll?: (scrollTop: number) => void,
 }
 
 
@@ -28,7 +28,6 @@ const Preview = (props: Props): JSX.Element => {
     appContainer,
     markdown, pagePath,
     inputRef,
-    onScroll,
   } = props;
 
   const [html, setHtml] = useState('');
@@ -89,7 +88,11 @@ const Preview = (props: Props): JSX.Element => {
     <div
       className="page-editor-preview-body"
       ref={inputRef}
-      onScroll={onScroll}
+      onScroll={(event: SyntheticEvent<HTMLDivElement>) => {
+        if (props.onScroll != null) {
+          props.onScroll(event.currentTarget.scrollTop);
+        }
+      }}
     >
       <RevisionBody
         {...props}
@@ -106,4 +109,9 @@ const Preview = (props: Props): JSX.Element => {
  */
 const PreviewWrapper = withUnstatedContainers(Preview, [AppContainer]);
 
-export default PreviewWrapper;
+// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
+const PreviewWrapper2 = (props): JSX.Element => {
+  return <PreviewWrapper {...props} />;
+};
+
+export default PreviewWrapper2;

+ 6 - 5
packages/app/src/components/PageEditorByHackmd.jsx

@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useState, useEffect } from 'react';
 
 import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
@@ -9,8 +9,8 @@ import EditorContainer from '~/client/services/EditorContainer';
 import PageContainer from '~/client/services/PageContainer';
 import { apiPost } from '~/client/util/apiv1-client';
 import { getOptionsToSave } from '~/client/util/editor';
-import { useSlackChannels } from '~/stores/context';
-import { useIsSlackEnabled } from '~/stores/editor';
+import { useCurrentPagePath } from '~/stores/context';
+import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
 import {
   useEditorMode, useSelectedGrant, useSelectedGrantGroupId, useSelectedGrantGroupName,
 } from '~/stores/ui';
@@ -431,8 +431,9 @@ const PageEditorByHackmdHOCWrapper = withUnstatedContainers(PageEditorByHackmd,
 
 const PageEditorByHackmdWrapper = (props) => {
   const { data: editorMode } = useEditorMode();
+  const { data: currentPagePath } = useCurrentPagePath();
+  const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
   const { data: isSlackEnabled } = useIsSlackEnabled();
-  const { data: slackChannels } = useSlackChannels();
   const { data: grant } = useSelectedGrant();
   const { data: grantGroupId } = useSelectedGrantGroupId();
   const { data: grantGroupName } = useSelectedGrantGroupName();
@@ -446,7 +447,7 @@ const PageEditorByHackmdWrapper = (props) => {
       {...props}
       editorMode={editorMode}
       isSlackEnabled={isSlackEnabled}
-      slackChannels={slackChannels}
+      slackChannels={slackChannelsData.toString()}
       grant={grant}
       grantGroupId={grantGroupId}
       grantGroupName={grantGroupName}

+ 1 - 1
packages/app/src/components/PageHistory.jsx

@@ -68,7 +68,7 @@ function PageHistory(props) {
   }
 
   return (
-    <div className="revision-history">
+    <div className="revision-history" data-testid="page-history">
       <PageRevisionTable
         pageHistoryContainer={pageHistoryContainer}
         revisionComparerContainer={revisionComparerContainer}

+ 3 - 1
packages/app/src/components/PageList/PageList.tsx

@@ -1,8 +1,10 @@
 import React from 'react';
+
 import { useTranslation } from 'react-i18next';
 
 import { IPageWithMeta } from '~/interfaces/page';
 import { OnDeletedFunction, OnPutBackedFunction } from '~/interfaces/ui';
+
 import { ForceHideMenuItems } from '../Common/Dropdown/PageItemControl';
 
 import { PageListItemL } from './PageListItemL';
@@ -53,7 +55,7 @@ const PageList = (props: Props): JSX.Element => {
 
   return (
     <div className="page-list">
-      <ul className="page-list-ul list-group-flush">
+      <ul className="page-list-ul list-group list-group-flush">
         {pageList}
       </ul>
     </div>

+ 1 - 0
packages/app/src/components/PageList/PageListItemL.tsx

@@ -225,6 +225,7 @@ const PageListItemLSubstance: ForwardRefRenderFunction<ISelectable, Props> = (pr
               {/* doropdown icon includes page control buttons */}
               <div className="ml-auto">
                 <PageItemControl
+                  alignRight
                   pageId={pageData._id}
                   pageInfo={isIPageInfoForListing(pageMeta) ? pageMeta : undefined}
                   isEnableActions={isEnableActions}

+ 8 - 1
packages/app/src/components/PagePresentationModal.jsx

@@ -1,4 +1,5 @@
 import React from 'react';
+
 import {
   Modal, ModalBody,
 } from 'reactstrap';
@@ -10,7 +11,13 @@ const PagePresentationModal = () => {
   const { data: presentationData, close: closePresentationModal } = usePagePresentationModal();
 
   return (
-    <Modal isOpen={presentationData.isOpened} toggle={closePresentationModal} className="grw-presentation-modal" unmountOnClose={false}>
+    <Modal
+      isOpen={presentationData.isOpened}
+      toggle={closePresentationModal}
+      data-testid="page-presentation-modal"
+      className="grw-presentation-modal"
+      unmountOnClose={false}
+    >
       <ModalBody className="modal-body">
         <iframe src={presentationData.href} />
       </ModalBody>

+ 32 - 54
packages/app/src/components/PageStatusAlert.jsx

@@ -1,6 +1,6 @@
 import React from 'react';
-import PropTypes from 'prop-types';
 
+import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
 
 import AppContainer from '~/client/services/AppContainer';
@@ -26,7 +26,6 @@ class PageStatusAlert extends React.Component {
     };
 
     this.getContentsForSomeoneEditingAlert = this.getContentsForSomeoneEditingAlert.bind(this);
-    this.getContentsForRevisionOutdated = this.getContentsForRevisionOutdated.bind(this);
     this.getContentsForDraftExistsAlert = this.getContentsForDraftExistsAlert.bind(this);
     this.getContentsForUpdatedAlert = this.getContentsForUpdatedAlert.bind(this);
     this.onClickResolveConflict = this.onClickResolveConflict.bind(this);
@@ -57,45 +56,6 @@ class PageStatusAlert extends React.Component {
     ];
   }
 
-  getContentsForRevisionOutdated() {
-    const { t, appContainer, pageContainer } = this.props;
-    const pageEditor = appContainer.getComponentInstance('PageEditor');
-
-    let markdownOnEdit = '';
-    let isConflictOnEdit = false;
-
-    if (pageEditor != null) {
-      markdownOnEdit = pageEditor.getMarkdown();
-      isConflictOnEdit = markdownOnEdit !== pageContainer.state.markdown;
-    }
-
-    return [
-      ['bg-warning', 'd-hackmd-none'],
-      <>
-        <i className="icon-fw icon-pencil"></i>
-        {t('modal_resolve_conflict.file_conflicting_with_newer_remote')}
-      </>,
-      <>
-        <button type="button" onClick={() => this.refreshPage()} className="btn btn-outline-white mr-4">
-          <i className="icon-fw icon-reload mr-1"></i>
-          {t('Load latest')}
-        </button>
-        {isConflictOnEdit
-          && (
-            <button
-              type="button"
-              onClick={this.onClickResolveConflict}
-              className="btn btn-outline-white"
-            >
-              <i className="fa fa-fw fa-file-text-o mr-1"></i>
-              {t('modal_resolve_conflict.resolve_conflict')}
-            </button>
-          )
-        }
-      </>,
-    ];
-  }
-
   getContentsForDraftExistsAlert(isRealtime) {
     const { t } = this.props;
     return [
@@ -112,20 +72,42 @@ class PageStatusAlert extends React.Component {
   }
 
   getContentsForUpdatedAlert() {
-    const { t } = this.props;
-    const label1 = t('edited this page');
-    const label2 = t('Load latest');
+    const { t, appContainer, pageContainer } = this.props;
+    const pageEditor = appContainer.getComponentInstance('PageEditor');
+
+    let isConflictOnEdit = false;
+
+    if (pageEditor != null) {
+      const markdownOnEdit = pageEditor.getMarkdown();
+      isConflictOnEdit = markdownOnEdit !== pageContainer.state.markdown;
+    }
+
+    const label1 = isConflictOnEdit
+      ? t('modal_resolve_conflict.file_conflicting_with_newer_remote')
+      : `${pageContainer.state.lastUpdateUsername} ${t('edited this page')}`;
 
     return [
       ['bg-warning'],
       <>
         <i className="icon-fw icon-bulb"></i>
-        {this.props.pageContainer.state.lastUpdateUsername} {label1}
+        {label1}
+      </>,
+      <>
+        <button type="button" onClick={() => this.refreshPage()} className="btn btn-outline-white mr-4">
+          <i className="icon-fw icon-reload mr-1"></i>
+          {t('Load latest')}
+        </button>
+        { isConflictOnEdit && (
+          <button
+            type="button"
+            onClick={this.onClickResolveConflict}
+            className="btn btn-outline-white"
+          >
+            <i className="fa fa-fw fa-file-text-o mr-1"></i>
+            {t('modal_resolve_conflict.resolve_conflict')}
+          </button>
+        )}
       </>,
-      <a href="#" className="btn btn-outline-white" onClick={this.refreshPage}>
-        <i className="icon-fw icon-reload mr-1"></i>
-        {label2}
-      </a>,
     ];
   }
 
@@ -139,12 +121,8 @@ class PageStatusAlert extends React.Component {
 
     let getContentsFunc = null;
 
-    // when conflicting on save
-    if (isRevisionOutdated) {
-      getContentsFunc = this.getContentsForRevisionOutdated;
-    }
     // when remote revision is newer than both
-    else if (isHackmdDocumentOutdated && isRevisionOutdated) {
+    if (isHackmdDocumentOutdated && isRevisionOutdated) {
       getContentsFunc = this.getContentsForUpdatedAlert;
     }
     // when someone editing with HackMD

+ 7 - 14
packages/app/src/components/SavePageControls.jsx

@@ -1,30 +1,27 @@
 import React from 'react';
-import PropTypes from 'prop-types';
 
+import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
-
 import {
   UncontrolledButtonDropdown, Button,
   DropdownToggle, DropdownMenu, DropdownItem,
 } from 'reactstrap';
 
-import loggerFactory from '~/utils/logger';
 
-import PageContainer from '~/client/services/PageContainer';
 import AppContainer from '~/client/services/AppContainer';
 import EditorContainer from '~/client/services/EditorContainer';
-
-import { withUnstatedContainers } from './UnstatedUtils';
-import GrantSelector from './SavePageControls/GrantSelector';
-
+import PageContainer from '~/client/services/PageContainer';
 import { getOptionsToSave } from '~/client/util/editor';
 
 // TODO: remove this when omitting unstated is completed
+import { useIsEditable } from '~/stores/context';
 import {
   useEditorMode, useSelectedGrant, useSelectedGrantGroupId, useSelectedGrantGroupName,
 } from '~/stores/ui';
-import { useIsEditable, useSlackChannels } from '~/stores/context';
-import { useIsSlackEnabled } from '~/stores/editor';
+import loggerFactory from '~/utils/logger';
+
+import GrantSelector from './SavePageControls/GrantSelector';
+import { withUnstatedContainers } from './UnstatedUtils';
 
 const logger = loggerFactory('growi:SavePageControls');
 
@@ -142,8 +139,6 @@ const SavePageControlsHOCWrapper = withUnstatedContainers(SavePageControls, [App
 const SavePageControlsWrapper = (props) => {
   const { data: isEditable } = useIsEditable();
   const { data: editorMode } = useEditorMode();
-  const { data: isSlackEnabled } = useIsSlackEnabled();
-  const { data: slackChannels } = useSlackChannels();
   const { data: grant, mutate: mutateGrant } = useSelectedGrant();
   const { data: grantGroupId, mutate: mutateGrantGroupId } = useSelectedGrantGroupId();
   const { data: grantGroupName, mutate: mutateGrantGroupName } = useSelectedGrantGroupName();
@@ -161,8 +156,6 @@ const SavePageControlsWrapper = (props) => {
     <SavePageControlsHOCWrapper
       {...props}
       editorMode={editorMode}
-      isSlackEnabled={isSlackEnabled}
-      slackChannels={slackChannels}
       grant={grant}
       grantGroupId={grantGroupId}
       grantGroupName={grantGroupName}

+ 26 - 32
packages/app/src/components/SearchPage/SearchResultContent.tsx

@@ -1,33 +1,31 @@
 import React, {
   FC, useCallback, useEffect, useRef,
 } from 'react';
-import { useTranslation } from 'react-i18next';
 
+import { useTranslation } from 'react-i18next';
 import { DropdownItem } from 'reactstrap';
 
+import { exportAsMarkdown } from '~/client/services/page-operation';
+import { toastSuccess } from '~/client/util/apiNotification';
+import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
 import { IPageToDeleteWithMeta, IPageToRenameWithMeta, IPageWithMeta } from '~/interfaces/page';
 import { IPageSearchMeta } from '~/interfaces/search';
 import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
+import {
+  usePageDuplicateModal, usePageRenameModal, usePageDeleteModal,
+} from '~/stores/modal';
+import { useDescendantsPageListForCurrentPathTermManager } from '~/stores/page';
 import { usePageTreeTermManager } from '~/stores/page-listing';
 import { useFullTextSearchTermManager } from '~/stores/search';
-import { useDescendantsPageListForCurrentPathTermManager } from '~/stores/page';
 
-import { exportAsMarkdown } from '~/client/services/page-operation';
-import { toastSuccess } from '~/client/util/apiNotification';
-
-import PageContentFooter from '../PageContentFooter';
-import PageComment from '../PageComment';
 
-import RevisionLoader from '../Page/RevisionLoader';
 import AppContainer from '../../client/services/AppContainer';
-import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
+import { AdditionalMenuItemsRendererProps, ForceHideMenuItems } from '../Common/Dropdown/PageItemControl';
 import { GrowiSubNavigation } from '../Navbar/GrowiSubNavigation';
 import { SubNavButtons } from '../Navbar/SubNavButtons';
-import { AdditionalMenuItemsRendererProps, ForceHideMenuItems } from '../Common/Dropdown/PageItemControl';
-
-import {
-  usePageDuplicateModal, usePageRenameModal, usePageDeleteModal,
-} from '~/stores/modal';
+import RevisionLoader from '../Page/RevisionLoader';
+import PageComment from '../PageComment';
+import PageContentFooter from '../PageContentFooter';
 
 
 type AdditionalMenuItemsProps = AdditionalMenuItemsRendererProps & {
@@ -179,24 +177,20 @@ export const SearchResultContent: FC<Props> = (props: Props) => {
       : page.revision._id;
 
     return (
-      <>
-        <div className="h-50 d-flex flex-column align-items-end justify-content-center">
-          <SubNavButtons
-            pageId={page._id}
-            revisionId={revisionId}
-            path={page.path}
-            showPageControlDropdown={showPageControlDropdown}
-            forceHideMenuItems={forceHideMenuItems}
-            additionalMenuItemRenderer={props => <AdditionalMenuItems {...props} pageId={page._id} revisionId={revisionId} />}
-            isCompactMode
-            onClickDuplicateMenuItem={duplicateItemClickedHandler}
-            onClickRenameMenuItem={renameItemClickedHandler}
-            onClickDeleteMenuItem={deleteItemClickedHandler}
-          />
-        </div>
-        <div className="h-50 d-flex flex-column align-items-end justify-content-center">
-        </div>
-      </>
+      <div className="d-flex flex-column align-items-end justify-content-center py-md-2">
+        <SubNavButtons
+          pageId={page._id}
+          revisionId={revisionId}
+          path={page.path}
+          showPageControlDropdown={showPageControlDropdown}
+          forceHideMenuItems={forceHideMenuItems}
+          additionalMenuItemRenderer={props => <AdditionalMenuItems {...props} pageId={page._id} revisionId={revisionId} />}
+          isCompactMode
+          onClickDuplicateMenuItem={duplicateItemClickedHandler}
+          onClickRenameMenuItem={renameItemClickedHandler}
+          onClickDeleteMenuItem={deleteItemClickedHandler}
+        />
+      </div>
     );
   }, [page, showPageControlDropdown, forceHideMenuItems, duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler]);
 

+ 21 - 14
packages/app/src/components/Sidebar/Tag.tsx

@@ -10,6 +10,7 @@ import TagList from '../TagList';
 
 
 const PAGING_LIMIT = 10;
+const TAG_CLOUD_LIMIT = 20;
 
 const Tag: FC = () => {
   const [activePage, setActivePage] = useState<number>(1);
@@ -20,6 +21,9 @@ const Tag: FC = () => {
   const totalCount: number = tagDataList?.totalCount || 0;
   const isLoading = tagDataList === undefined && error == null;
 
+  const { data: tagDataCloud } = useSWRxTagsList(TAG_CLOUD_LIMIT, 0);
+  const tagCloudData: IDataTagCount[] = tagDataCloud?.data || [];
+
   const { t } = useTranslation('');
 
   const setOffsetByPageNumber = useCallback((selectedPageNumber: number) => {
@@ -44,21 +48,8 @@ const Tag: FC = () => {
           <i className="icon icon-reload"></i>
         </button>
       </div>
-      <h2 className="my-3">{t('popular_tags')}</h2>
-
-      <div className="px-3 text-center">
-        <TagCloudBox tags={tagData} />
-      </div>
 
-      <div className="d-flex justify-content-center my-5">
-        <button
-          className="btn btn-primary rounded px-5"
-          type="button"
-          onClick={() => { window.location.href = '/tags' }}
-        >
-          {t('Check All tags')}
-        </button>
-      </div>
+      <h3 className="my-3">{t('tag_list')}</h3>
 
       { isLoading
         ? (
@@ -76,6 +67,22 @@ const Tag: FC = () => {
           />
         )
       }
+
+      <div className="d-flex justify-content-center my-5">
+        <button
+          className="btn btn-primary rounded px-4"
+          type="button"
+          onClick={() => { window.location.href = '/tags' }}
+        >
+          {t('Check All tags')}
+        </button>
+      </div>
+
+      <h3 className="my-3">{t('popular_tags')}</h3>
+
+      <div className="text-center">
+        <TagCloudBox tags={tagCloudData} />
+      </div>
     </div>
   );
 

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

@@ -1,5 +1,6 @@
 /* eslint-disable react/prop-types */
 import React, { FC } from 'react';
+
 import { useTranslation } from 'react-i18next';
 import { PopoverBody, PopoverHeader, UncontrolledPopover } from 'reactstrap';
 

+ 13 - 4
packages/app/src/components/TableOfContents.jsx

@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect } from 'react';
+import React, { useCallback, useEffect, useState } from 'react';
 
 import PropTypes from 'prop-types';
 
@@ -25,6 +25,8 @@ const TableOfContents = (props) => {
   const { pageUser } = pageContainer.state;
   const isUserPage = pageUser != null;
 
+  const [tocHtml, setTocHtml] = useState('');
+
   const calcViewHeight = useCallback(() => {
     // calculate absolute top of '#revision-toc' element
     const parentElem = document.querySelector('.grw-side-contents-container');
@@ -45,15 +47,22 @@ const TableOfContents = (props) => {
     return bottom - (containerTop + containerPaddingTop);
   }, [isUserPage]);
 
-  const { tocHtml } = pageContainer.state;
-
-  // execute after generation toc html
   useEffect(() => {
     const tocDom = document.getElementById('revision-toc-content');
     const anchorsInToc = Array.from(tocDom.getElementsByTagName('a'));
     addSmoothScrollEvent(anchorsInToc, blinkElem);
   }, [tocHtml]);
 
+  // set handler to render ToC
+  useEffect(() => {
+    const handler = html => setTocHtml(html);
+    window.globalEmitter.on('renderTocHtml', handler);
+
+    return function cleanup() {
+      window.globalEmitter.removeListener('renderTocHtml', handler);
+    };
+  }, []);
+
   return (
     <StickyStretchableScroller
       stickyElemSelector=".grw-side-contents-sticky-container"

+ 13 - 24
packages/app/src/components/TagCloudBox.tsx

@@ -1,7 +1,5 @@
 import React, { FC, memo } from 'react';
 
-import { TagCloud } from 'react-tagcloud';
-
 import { IDataTagCount } from '~/interfaces/tag';
 
 type Props = {
@@ -16,34 +14,25 @@ const defaultProps = {
   isDisableRandomColor: true,
 };
 
-const MIN_FONT_SIZE = 10;
-const MAX_FONT_SIZE = 24;
 const MAX_TAG_TEXT_LENGTH = 8;
 
 const TagCloudBox: FC<Props> = memo((props:(Props & typeof defaultProps)) => {
-  const {
-    tags, minSize, maxSize, isDisableRandomColor,
-  } = props;
+  const { tags } = props;
   const maxTagTextLength: number = props.maxTagTextLength ?? MAX_TAG_TEXT_LENGTH;
 
+  const tagElements = tags.map((tag:IDataTagCount) => {
+    const tagNameFormat = (tag.name).length > maxTagTextLength ? `${(tag.name).slice(0, maxTagTextLength)}...` : tag.name;
+    return (
+      <a key={tag.name} href={`/_search?q=tag:${tag.name}`} className="grw-tag-label badge badge-secondary mr-2">
+        {tagNameFormat}
+      </a>
+    );
+  });
+
   return (
-    <>
-      <TagCloud
-        minSize={minSize ?? MIN_FONT_SIZE}
-        maxSize={maxSize ?? MAX_FONT_SIZE}
-        tags={tags.map((tag:IDataTagCount) => {
-          return {
-            // text truncation
-            value: (tag.name).length > maxTagTextLength ? `${(tag.name).slice(0, maxTagTextLength)}...` : tag.name,
-            count: tag.count,
-          };
-        })}
-        disableRandomColor={isDisableRandomColor}
-        style={{ cursor: 'pointer' }}
-        className="simple-cloud text-secondary"
-        onClick={(target) => { window.location.href = `/_search?q=tag:${encodeURIComponent(target.value)}` }}
-      />
-    </>
+    <div className="grw-popular-tag-labels">
+      {tagElements}
+    </div>
   );
 
 });

+ 2 - 2
packages/app/src/components/TagList.tsx

@@ -38,7 +38,7 @@ const TagList: FC<TagListProps> = (props:(TagListProps & typeof defaultProps)) =
           href={`/_search?q=tag:${encodeURIComponent(tag.name)}`}
           className={tagListClasses}
         >
-          <div className="text-truncate">{tag.name}</div>
+          <div className="text-truncate list-tag-name">{tag.name}</div>
           <div className="ml-4 my-auto py-1 px-2 list-tag-count badge badge-secondary text-white">{tag.count}</div>
         </a>
       );
@@ -51,7 +51,7 @@ const TagList: FC<TagListProps> = (props:(TagListProps & typeof defaultProps)) =
 
   return (
     <>
-      <ul className="list-group text-left mb-4">
+      <ul className="list-group text-left mb-5">
         {generateTagList(tagData)}
       </ul>
       {isPaginationShown

+ 11 - 0
packages/app/src/interfaces/attachment.ts

@@ -0,0 +1,11 @@
+import { Ref } from './common';
+import { IPage } from './page';
+import { IUser } from './user';
+
+export type IAttachment = {
+  page?: Ref<IPage>,
+  creator?: Ref<IUser>,
+
+  // virtual property
+  filePathProxied: string,
+};

+ 3 - 0
packages/app/src/interfaces/user-trigger-notification.ts

@@ -0,0 +1,3 @@
+
+type SlackChannel = string;
+export type SlackChannels = {[updatePost: string]: SlackChannel[]}

+ 4 - 0
packages/app/src/interfaces/user.ts

@@ -1,3 +1,4 @@
+import { IAttachment } from './attachment';
 import { Ref } from './common';
 import { HasObjectId } from './has-object-id';
 
@@ -6,7 +7,10 @@ export type IUser = {
   username: string;
   email: string;
   password: string;
+  image?: string, // for backward conpatibility
+  imageAttachment?: Ref<IAttachment>,
   imageUrlCached: string;
+  isGravatarEnabled: boolean,
   admin: boolean;
 }
 

+ 4 - 4
packages/app/src/server/models/attachment.js

@@ -6,10 +6,10 @@ import loggerFactory from '~/utils/logger';
 // eslint-disable-next-line no-unused-vars
 const path = require('path');
 
+const { addSeconds } = require('date-fns');
 const mongoose = require('mongoose');
-const uniqueValidator = require('mongoose-unique-validator');
 const mongoosePaginate = require('mongoose-paginate-v2');
-const { addSeconds } = require('date-fns');
+const uniqueValidator = require('mongoose-unique-validator');
 
 // eslint-disable-next-line no-unused-vars
 const logger = loggerFactory('growi:models:attachment');
@@ -32,9 +32,10 @@ module.exports = function(crowi) {
     originalName: { type: String },
     fileFormat: { type: String, required: true },
     fileSize: { type: Number, default: 0 },
-    createdAt: { type: Date, default: Date.now },
     temporaryUrlCached: { type: String },
     temporaryUrlExpiredAt: { type: Date },
+  }, {
+    timestamps: { createdAt: true, updatedAt: false },
   });
   attachmentSchema.plugin(uniqueValidator);
   attachmentSchema.plugin(mongoosePaginate);
@@ -67,7 +68,6 @@ module.exports = function(crowi) {
     attachment.fileName = fileName;
     attachment.fileFormat = fileFormat;
     attachment.fileSize = fileSize;
-    attachment.createdAt = Date.now();
 
     return attachment;
   };

+ 3 - 2
packages/app/src/server/models/bookmark.js

@@ -16,7 +16,8 @@ module.exports = function(crowi) {
   bookmarkSchema = new mongoose.Schema({
     page: { type: ObjectId, ref: 'Page', index: true },
     user: { type: ObjectId, ref: 'User', index: true },
-    createdAt: { type: Date, default: Date.now },
+  }, {
+    timestamps: { createdAt: true, updatedAt: false },
   });
   bookmarkSchema.index({ page: 1, user: 1 }, { unique: true });
   bookmarkSchema.plugin(mongoosePaginate);
@@ -61,7 +62,7 @@ module.exports = function(crowi) {
   bookmarkSchema.statics.add = async function(page, user) {
     const Bookmark = this;
 
-    const newBookmark = new Bookmark({ page, user, createdAt: Date.now() });
+    const newBookmark = new Bookmark({ page, user });
 
     try {
       const bookmark = await newBookmark.save();

+ 2 - 1
packages/app/src/server/models/external-account.js

@@ -15,7 +15,8 @@ const schema = new mongoose.Schema({
   providerType: { type: String, required: true },
   accountId: { type: String, required: true },
   user: { type: ObjectId, ref: 'User', required: true },
-  createdAt: { type: Date, default: Date.now, required: true },
+}, {
+  timestamps: { createdAt: true, updatedAt: false },
 });
 // compound index
 schema.index({ providerType: 1, accountId: 1 }, { unique: true });

+ 2 - 4
packages/app/src/server/models/in-app-notification.ts

@@ -71,14 +71,12 @@ const inAppNotificationSchema = new Schema<InAppNotificationDocument, InAppNotif
     index: true,
     require: true,
   },
-  createdAt: {
-    type: Date,
-    default: new Date(),
-  },
   snapshot: {
     type: String,
     require: true,
   },
+}, {
+  timestamps: { createdAt: true, updatedAt: false },
 });
 inAppNotificationSchema.plugin(mongoosePaginate);
 

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

@@ -99,15 +99,14 @@ const schema = new Schema<PageDocument, PageModel>({
   liker: [{ type: ObjectId, ref: 'User' }],
   seenUsers: [{ type: ObjectId, ref: 'User' }],
   commentCount: { type: Number, default: 0 },
-  slackChannels: { type: String },
   pageIdOnHackmd: { type: String },
   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
-  createdAt: { type: Date, default: new Date() },
-  updatedAt: { type: Date, default: new Date() },
+  updatedAt: { type: Date, default: Date.now }, // Do not use timetamps for updatedAt because it breaks 'updateMetadata: false' option
   deleteUser: { type: ObjectId, ref: 'User' },
   deletedAt: { type: Date },
 }, {
+  timestamps: { createdAt: true, updatedAt: false },
   toJSON: { getters: true },
   toObject: { getters: true },
 });

+ 2 - 2
packages/app/src/server/models/revision.js

@@ -28,8 +28,9 @@ module.exports = function(crowi) {
     },
     format: { type: String, default: 'markdown' },
     author: { type: ObjectId, ref: 'User' },
-    createdAt: { type: Date, default: Date.now },
     hasDiffToPrev: { type: Boolean },
+  }, {
+    timestamps: { createdAt: true, updatedAt: false },
   });
   revisionSchema.plugin(mongoosePaginate);
 
@@ -55,7 +56,6 @@ module.exports = function(crowi) {
     newRevision.body = body;
     newRevision.format = format;
     newRevision.author = user._id;
-    newRevision.createdAt = Date.now();
     if (pageData.revision != null) {
       newRevision.hasDiffToPrev = body !== previousBody;
     }

+ 3 - 2
packages/app/src/server/models/share-link.js

@@ -2,8 +2,8 @@
 /* eslint-disable no-return-await */
 
 const mongoose = require('mongoose');
-const uniqueValidator = require('mongoose-unique-validator');
 const mongoosePaginate = require('mongoose-paginate-v2');
+const uniqueValidator = require('mongoose-unique-validator');
 
 const ObjectId = mongoose.Schema.Types.ObjectId;
 
@@ -19,7 +19,8 @@ const schema = new mongoose.Schema({
   },
   expiredAt: { type: Date },
   description: { type: String },
-  createdAt: { type: Date, default: Date.now, required: true },
+}, {
+  timestamps: { createdAt: true, updatedAt: false },
 });
 schema.plugin(mongoosePaginate);
 schema.plugin(uniqueValidator);

+ 2 - 1
packages/app/src/server/models/subscription.ts

@@ -50,7 +50,8 @@ const subscriptionSchema = new Schema<SubscriptionDocument, SubscriptionModel>({
     require: true,
     enum: AllSubscriptionStatusType,
   },
-  createdAt: { type: Date, default: new Date() },
+}, {
+  timestamps: true,
 });
 
 subscriptionSchema.methods.isSubscribing = function() {

+ 3 - 3
packages/app/src/server/models/update-post.ts

@@ -1,9 +1,9 @@
 /* eslint-disable @typescript-eslint/no-explicit-any */
 
+import { getOrCreateModel } from '@growi/core';
 import {
   Types, Schema, Model, Document,
 } from 'mongoose';
-import { getOrCreateModel } from '@growi/core';
 
 export interface IUpdatePost {
   pathPattern: string
@@ -36,7 +36,8 @@ const updatePostSchema = new Schema<UpdatePostDocument, UpdatePostModel>({
   channel: { type: String, required: true },
   provider: { type: String, required: true },
   creator: { type: Schema.Types.ObjectId, ref: 'User', index: true },
-  createdAt: { type: Date, default: new Date(Date.now()) },
+}, {
+  timestamps: true,
 });
 
 updatePostSchema.statics.normalizeChannelName = function(channel) {
@@ -115,7 +116,6 @@ updatePostSchema.statics.createUpdatePost = async function(pathPattern, channel,
     channel: this.normalizeChannelName(channel),
     provider,
     creator,
-    createdAt: Date.now(),
   });
 };
 

+ 2 - 1
packages/app/src/server/models/user-group-relation.js

@@ -12,7 +12,8 @@ const ObjectId = mongoose.Schema.Types.ObjectId;
 const schema = new mongoose.Schema({
   relatedGroup: { type: ObjectId, ref: 'UserGroup', required: true },
   relatedUser: { type: ObjectId, ref: 'User', required: true },
-  createdAt: { type: Date, default: Date.now, required: true },
+}, {
+  timestamps: { createdAt: true, updatedAt: false },
 });
 schema.plugin(mongoosePaginate);
 schema.plugin(uniqueValidator);

+ 4 - 3
packages/app/src/server/models/user-group.ts

@@ -1,8 +1,8 @@
+import { getOrCreateModel } from '@growi/core';
 import mongoose, {
-  Types, Schema, Model, Document,
+  Schema, Model, Document,
 } from 'mongoose';
 import mongoosePaginate from 'mongoose-paginate-v2';
-import { getOrCreateModel } from '@growi/core';
 
 import { IUserGroup } from '~/interfaces/user';
 
@@ -22,9 +22,10 @@ const ObjectId = mongoose.Schema.Types.ObjectId;
 
 const schema = new Schema<UserGroupDocument, UserGroupModel>({
   name: { type: String, required: true, unique: true },
-  createdAt: { type: Date, default: new Date() },
   parent: { type: ObjectId, ref: 'UserGroup', index: true },
   description: { type: String, default: '' },
+}, {
+  timestamps: true,
 });
 schema.plugin(mongoosePaginate);
 

+ 6 - 8
packages/app/src/server/models/user-registration-order.ts

@@ -1,11 +1,12 @@
+import crypto from 'crypto';
+
+import { getOrCreateModel } from '@growi/core';
+import { addHours } from 'date-fns';
 import {
   Schema, Model, Document,
 } from 'mongoose';
-
-import { addHours } from 'date-fns';
 import uniqueValidator from 'mongoose-unique-validator';
-import crypto from 'crypto';
-import { getOrCreateModel } from '@growi/core';
+
 
 export interface IUserRegistrationOrder {
   token: string,
@@ -35,10 +36,7 @@ const schema = new Schema<UserRegistrationOrderDocument, UserRegistrationOrderMo
   isRevoked: { type: Boolean, default: false, required: true },
   expiredAt: { type: Date, default: expiredAt, required: true },
 }, {
-  timestamps: {
-    createdAt: true,
-    updatedAt: false,
-  },
+  timestamps: true,
 });
 schema.plugin(uniqueValidator);
 

+ 4 - 6
packages/app/src/server/models/user.js

@@ -1,6 +1,8 @@
 /* eslint-disable no-use-before-define */
+import { generateGravatarSrc } from '~/utils/gravatar';
 import loggerFactory from '~/utils/logger';
 
+
 const crypto = require('crypto');
 
 const debug = require('debug')('growi:models:user');
@@ -65,11 +67,11 @@ module.exports = function(crowi) {
     status: {
       type: Number, required: true, default: STATUS_ACTIVE, index: true,
     },
-    createdAt: { type: Date, default: Date.now },
     lastLoginAt: { type: Date },
     admin: { type: Boolean, default: 0, index: true },
     isInvitationEmailSended: { type: Boolean, default: false },
   }, {
+    timestamps: true,
     toObject: {
       transform: (doc, ret, opt) => {
         return omitInsecureAttributes(ret);
@@ -227,9 +229,7 @@ module.exports = function(crowi) {
 
   userSchema.methods.generateImageUrlCached = async function() {
     if (this.isGravatarEnabled) {
-      const email = this.email || '';
-      const hash = md5(email.trim().toLowerCase());
-      return `https://gravatar.com/avatar/${hash}`;
+      return generateGravatarSrc(this.email);
     }
     if (this.image != null) {
       return this.image;
@@ -542,7 +542,6 @@ module.exports = function(crowi) {
     newUser.username = tmpUsername;
     newUser.email = email;
     newUser.setPassword(password);
-    newUser.createdAt = Date.now();
     newUser.status = STATUS_INVITED;
 
     const globalLang = configManager.getConfig('crowi', 'app:globalLang');
@@ -632,7 +631,6 @@ module.exports = function(crowi) {
     if (lang != null) {
       newUser.lang = lang;
     }
-    newUser.createdAt = Date.now();
     newUser.status = status || decideUserStatusOnRegistration();
 
     newUser.save((err, userData) => {

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

@@ -245,8 +245,8 @@ module.exports = (crowi) => {
    *                schema:
    *                  $ref: '#/components/schemas/Page'
    */
-  router.get('/', accessTokenParser, loginRequired, validator.getPage, apiV3FormValidator, async(req, res) => {
-    const { pageId, path } = req.query;
+  router.get('/', certifySharedPage, accessTokenParser, loginRequired, validator.getPage, apiV3FormValidator, async(req, res) => {
+    const { pageId, path, user } = req.query;
 
     if (pageId == null && path == null) {
       return res.apiv3Err(new ErrorV3('Parameter path or pageId is required.', 'invalid-request'));
@@ -255,10 +255,10 @@ module.exports = (crowi) => {
     let page;
     try {
       if (pageId != null) { // prioritized
-        page = await Page.findByIdAndViewer(pageId, req.user);
+        page = await Page.findByIdAndViewer(pageId, user);
       }
       else {
-        page = await Page.findByPathAndViewer(path, req.user);
+        page = await Page.findByPathAndViewer(path, user);
       }
     }
     catch (err) {

+ 6 - 1
packages/app/src/server/routes/attachment.js

@@ -7,7 +7,6 @@ const logger = loggerFactory('growi:routes:attachment');
 
 const { serializePageSecurely } = require('../models/serializers/page-serializer');
 const { serializeRevisionSecurely } = require('../models/serializers/revision-serializer');
-
 const ApiResponse = require('../util/apiResponse');
 
 /**
@@ -231,6 +230,12 @@ module.exports = function(crowi, app) {
       'Last-Modified': attachment.createdAt.toUTCString(),
     });
 
+    if (!attachment.fileSize) {
+      res.set({
+        'Content-Length': attachment.fileSize,
+      });
+    }
+
     // download
     if (forceDownload) {
       res.set({

+ 71 - 71
packages/app/src/server/service/file-uploader/aws.js → packages/app/src/server/service/file-uploader/aws.ts

@@ -1,41 +1,57 @@
+import {
+  S3Client,
+  HeadObjectCommand,
+  GetObjectCommand,
+  DeleteObjectsCommand,
+  PutObjectCommand,
+  DeleteObjectCommand,
+  GetObjectCommandOutput,
+} from '@aws-sdk/client-s3';
+import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
+import urljoin from 'url-join';
+
 import loggerFactory from '~/utils/logger';
 
-const logger = loggerFactory('growi:service:fileUploaderAws');
 
-const urljoin = require('url-join');
-const aws = require('aws-sdk');
+const logger = loggerFactory('growi:service:fileUploaderAws');
 
-module.exports = function(crowi) {
+type AwsCredential = {
+  accessKeyId: string,
+  secretAccessKey: string
+}
+type AwsConfig = {
+  credentials: AwsCredential,
+  region: string,
+  endpoint: string,
+  bucket: string,
+  forcePathStyle?: boolean
+}
+
+module.exports = (crowi) => {
   const Uploader = require('./uploader');
   const { configManager } = crowi;
   const lib = new Uploader(crowi);
 
-  function getAwsConfig() {
+  const getAwsConfig = (): AwsConfig => {
     return {
-      accessKeyId: configManager.getConfig('crowi', 'aws:s3AccessKeyId'),
-      secretAccessKey: configManager.getConfig('crowi', 'aws:s3SecretAccessKey'),
+      credentials: {
+        accessKeyId: configManager.getConfig('crowi', 'aws:s3AccessKeyId'),
+        secretAccessKey: configManager.getConfig('crowi', 'aws:s3SecretAccessKey'),
+      },
       region: configManager.getConfig('crowi', 'aws:s3Region'),
+      endpoint: configManager.getConfig('crowi', 'aws:s3CustomEndpoint'),
       bucket: configManager.getConfig('crowi', 'aws:s3Bucket'),
-      customEndpoint: configManager.getConfig('crowi', 'aws:s3CustomEndpoint'),
+      forcePathStyle: configManager.getConfig('crowi', 'aws:s3CustomEndpoint') != null, // s3ForcePathStyle renamed to forcePathStyle in v3
     };
-  }
-
-  function S3Factory() {
-    const awsConfig = getAwsConfig();
-
-    aws.config.update({
-      accessKeyId: awsConfig.accessKeyId,
-      secretAccessKey: awsConfig.secretAccessKey,
-      region: awsConfig.region,
-      s3ForcePathStyle: awsConfig.customEndpoint ? true : undefined,
-    });
+  };
 
-    // undefined & null & '' => default endpoint (genuine S3)
-    return new aws.S3({ endpoint: awsConfig.customEndpoint || undefined });
-  }
+  const S3Factory = (): S3Client => {
+    const config = getAwsConfig();
+    return new S3Client(config);
+  };
 
-  function getFilePathOnStorage(attachment) {
-    if (attachment.filePath != null) { // backward compatibility for v3.3.x or below
+  const getFilePathOnStorage = (attachment) => {
+    if (attachment.filePath != null) {
       return attachment.filePath;
     }
 
@@ -45,41 +61,37 @@ module.exports = function(crowi) {
     const filePath = urljoin(dirName, attachment.fileName);
 
     return filePath;
-  }
+  };
 
-  async function isFileExists(s3, params) {
-    // check file exists
+  const isFileExists = async(s3: S3Client, params) => {
     try {
-      await s3.headObject(params).promise();
+      await s3.send(new HeadObjectCommand(params));
     }
     catch (err) {
       if (err != null && err.code === 'NotFound') {
         return false;
       }
-
-      // error except for 'NotFound
       throw err;
     }
-
     return true;
-  }
+  };
 
-  lib.isValidUploadSettings = function() {
-    return this.configManager.getConfig('crowi', 'aws:s3AccessKeyId') != null
-      && this.configManager.getConfig('crowi', 'aws:s3SecretAccessKey') != null
+  lib.isValidUploadSettings = () => {
+    return configManager.getConfig('crowi', 'aws:s3AccessKeyId') != null
+      && configManager.getConfig('crowi', 'aws:s3SecretAccessKey') != null
       && (
-        this.configManager.getConfig('crowi', 'aws:s3Region') != null
-          || this.configManager.getConfig('crowi', 'aws:s3CustomEndpoint') != null
+        configManager.getConfig('crowi', 'aws:s3Region') != null
+          || configManager.getConfig('crowi', 'aws:s3CustomEndpoint') != null
       )
-      && this.configManager.getConfig('crowi', 'aws:s3Bucket') != null;
+      && configManager.getConfig('crowi', 'aws:s3Bucket') != null;
   };
 
-  lib.canRespond = function() {
-    return !this.configManager.getConfig('crowi', 'aws:referenceFileWithRelayMode');
+  lib.canRespond = () => {
+    return !configManager.getConfig('crowi', 'aws:referenceFileWithRelayMode');
   };
 
-  lib.respond = async function(res, attachment) {
-    if (!this.getIsUploadable()) {
+  lib.respond = async(res, attachment) => {
+    if (!lib.getIsUploadable()) {
       throw new Error('AWS is not configured.');
     }
     const temporaryUrl = attachment.getValidTemporaryUrl();
@@ -90,16 +102,16 @@ module.exports = function(crowi) {
     const s3 = S3Factory();
     const awsConfig = getAwsConfig();
     const filePath = getFilePathOnStorage(attachment);
-    const lifetimeSecForTemporaryUrl = this.configManager.getConfig('crowi', 'aws:lifetimeSecForTemporaryUrl');
+    const lifetimeSecForTemporaryUrl = configManager.getConfig('crowi', 'aws:lifetimeSecForTemporaryUrl');
 
     // issue signed url (default: expires 120 seconds)
     // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getSignedUrl-property
     const params = {
       Bucket: awsConfig.bucket,
       Key: filePath,
-      Expires: lifetimeSecForTemporaryUrl,
     };
-    const signedUrl = s3.getSignedUrl('getObject', params);
+    const signedUrl = await getSignedUrl(s3, new GetObjectCommand(params), { expiresIn: lifetimeSecForTemporaryUrl });
+
 
     res.redirect(signedUrl);
 
@@ -112,13 +124,13 @@ module.exports = function(crowi) {
 
   };
 
-  lib.deleteFile = async function(attachment) {
+  lib.deleteFile = async(attachment) => {
     const filePath = getFilePathOnStorage(attachment);
     return lib.deleteFileByFilePath(filePath);
   };
 
-  lib.deleteFiles = async function(attachments) {
-    if (!this.getIsUploadable()) {
+  lib.deleteFiles = async(attachments) => {
+    if (!lib.getIsUploadable()) {
       throw new Error('AWS is not configured.');
     }
     const s3 = S3Factory();
@@ -132,11 +144,11 @@ module.exports = function(crowi) {
       Bucket: awsConfig.bucket,
       Delete: { Objects: filePaths },
     };
-    return s3.deleteObjects(totalParams).promise();
+    return s3.send(new DeleteObjectsCommand(totalParams));
   };
 
-  lib.deleteFileByFilePath = async function(filePath) {
-    if (!this.getIsUploadable()) {
+  lib.deleteFileByFilePath = async(filePath) => {
+    if (!lib.getIsUploadable()) {
       throw new Error('AWS is not configured.');
     }
     const s3 = S3Factory();
@@ -154,11 +166,11 @@ module.exports = function(crowi) {
       return;
     }
 
-    return s3.deleteObject(params).promise();
+    return s3.send(new DeleteObjectCommand(params));
   };
 
-  lib.uploadFile = function(fileStream, attachment) {
-    if (!this.getIsUploadable()) {
+  lib.uploadFile = async(fileStream, attachment) => {
+    if (!lib.getIsUploadable()) {
       throw new Error('AWS is not configured.');
     }
 
@@ -176,17 +188,11 @@ module.exports = function(crowi) {
       ACL: 'public-read',
     };
 
-    return s3.upload(params).promise();
+    return s3.send(new PutObjectCommand(params));
   };
 
-  /**
-   * Find data substance
-   *
-   * @param {Attachment} attachment
-   * @return {stream.Readable} readable stream
-   */
-  lib.findDeliveryFile = async function(attachment) {
-    if (!this.getIsReadable()) {
+  lib.findDeliveryFile = async(attachment) => {
+    if (!lib.getIsReadable()) {
       throw new Error('AWS is not configured.');
     }
 
@@ -205,9 +211,9 @@ module.exports = function(crowi) {
       throw new Error(`Any object that relate to the Attachment (${filePath}) does not exist in AWS S3`);
     }
 
-    let stream;
+    let stream : GetObjectCommandOutput['Body'];
     try {
-      stream = s3.getObject(params).createReadStream();
+      stream = (await s3.send(new GetObjectCommand(params))).Body;
     }
     catch (err) {
       logger.error(err);
@@ -218,12 +224,6 @@ module.exports = function(crowi) {
     return stream;
   };
 
-  /**
-   * check the file size limit
-   *
-   * In detail, the followings are checked.
-   * - per-file size limit (specified by MAX_FILE_SIZE)
-   */
   lib.checkLimit = async(uploadFileSize) => {
     const maxFileSize = crowi.configManager.getConfig('crowi', 'app:maxFileSize');
     const totalLimit = crowi.configManager.getConfig('crowi', 'app:fileUploadTotalLimit');

+ 18 - 8
packages/app/src/server/service/import.js

@@ -1,23 +1,24 @@
+import gc from 'expose-gc/function';
+
 import loggerFactory from '~/utils/logger';
 
-const logger = loggerFactory('growi:services:ImportService'); // eslint-disable-line no-unused-vars
 const fs = require('fs');
 const path = require('path');
-
-const isIsoDate = require('is-iso-date');
-const parseISO = require('date-fns/parseISO');
-
 const { Writable, Transform } = require('stream');
+
 const JSONStream = require('JSONStream');
+const parseISO = require('date-fns/parseISO');
+const isIsoDate = require('is-iso-date');
+const mongoose = require('mongoose');
 const streamToPromise = require('stream-to-promise');
 const unzipper = require('unzipper');
 
-const mongoose = require('mongoose');
+const CollectionProgressingStatus = require('../models/vo/collection-progressing-status');
+const { createBatchStream } = require('../util/batch-stream');
 
 const { ObjectId } = mongoose.Types;
 
-const { createBatchStream } = require('../util/batch-stream');
-const CollectionProgressingStatus = require('../models/vo/collection-progressing-status');
+const logger = loggerFactory('growi:services:ImportService'); // eslint-disable-line no-unused-vars
 
 
 const BULK_IMPORT_SIZE = 100;
@@ -286,6 +287,15 @@ class ImportService {
 
           emitProgressEvent(collectionProgress, errors);
 
+          try {
+            // First aid to prevent unexplained memory leaks
+            logger.info('global.gc() invoked.');
+            gc();
+          }
+          catch (err) {
+            logger.error('fail garbage collection: ', err);
+          }
+
           callback();
         },
         final(callback) {

+ 14 - 6
packages/app/src/server/service/page.ts

@@ -2297,7 +2297,7 @@ class PageService {
         grantedUsers: notEmptyParent.grantedUsers,
       };
 
-      systematicallyCreatedPage = await this.createBySystem(
+      systematicallyCreatedPage = await this.forceCreateBySystem(
         path,
         '',
         options,
@@ -3371,7 +3371,7 @@ class PageService {
     return savedPage;
   }
 
-  private async canProcessCreateBySystem(
+  private async canProcessForceCreateBySystem(
       path: string,
       grantData: {
         grant: number,
@@ -3382,7 +3382,15 @@ class PageService {
     return this.canProcessCreate(path, grantData, false);
   }
 
-  async createBySystem(path: string, body: string, options: PageCreateOptions & { grantedUsers?: ObjectIdLike[] }): Promise<PageDocument> {
+  /**
+   * @private
+   * This method receives the same arguments as the PageService.create method does except for the added type '{ grantedUsers?: ObjectIdLike[] }'.
+   * This additional value is used to determine the grantedUser of the page to be created by system.
+   * This method must not run isGrantNormalized method to validate grant. **If necessary, run it before use this method.**
+   * -- Reason 1: This is because it is not expected to use this method when the grant validation is required.
+   * -- Reason 2: This is because it is not expected to use this method when the program cannot determine the operator.
+   */
+  private async forceCreateBySystem(path: string, body: string, options: PageCreateOptions & { grantedUsers?: ObjectIdLike[] }): Promise<PageDocument> {
     const Page = mongoose.model('Page') as unknown as PageModel;
 
     const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
@@ -3412,9 +3420,9 @@ class PageService {
     if (isGrantOwner && grantedUsers?.length !== 1) {
       throw Error('grantedUser must exist when grant is GRANT_OWNER');
     }
-    const canProcessCreateBySystem = await this.canProcessCreateBySystem(path, grantData);
-    if (!canProcessCreateBySystem) {
-      throw Error('Cannnot process createBySystem');
+    const canProcessForceCreateBySystem = await this.canProcessForceCreateBySystem(path, grantData);
+    if (!canProcessForceCreateBySystem) {
+      throw Error('Cannnot process forceCreateBySystem');
     }
 
     // Prepare a page document

+ 3 - 1
packages/app/src/server/service/search-delegator/elasticsearch.ts

@@ -3,6 +3,7 @@ import { URL } from 'url';
 
 import elasticsearch6 from '@elastic/elasticsearch6';
 import elasticsearch7 from '@elastic/elasticsearch7';
+import gc from 'expose-gc/function';
 import mongoose from 'mongoose';
 import streamToPromise from 'stream-to-promise';
 
@@ -593,7 +594,8 @@ class ElasticsearchDelegator implements SearchDelegator<Data, ESTermsKey, ESQuer
         if (invokeGarbageCollection) {
           try {
             // First aid to prevent unexplained memory leaks
-            global.gc();
+            logger.info('global.gc() invoked.');
+            gc();
           }
           catch (err) {
             logger.error('fail garbage collection: ', err);

+ 0 - 11
packages/app/src/server/service/user-notification/index.ts

@@ -49,7 +49,6 @@ export class UserNotificationService {
 
     // "dev,slacktest" => [dev,slacktest]
     const slackChannels: (string|null)[] = toArrayFromCsv(slackChannelsStr);
-    await this.putDefaultChannelIfEmpty(page.path, slackChannels);
 
     const appTitle = appService.getAppTitle();
     const siteUrl = appService.getSiteUrl();
@@ -69,14 +68,4 @@ export class UserNotificationService {
     return Promise.allSettled(promises);
   }
 
-  private async putDefaultChannelIfEmpty(pagePath:string, slackChannels: (string|null)[]): Promise<void> {
-    const updatePosts = await UpdatePost.findSettingsByPath(pagePath);
-    slackChannels.push(...(updatePosts).map(up => up.channel));
-
-    // insert null if empty to notify once
-    if (slackChannels.length === 0) {
-      slackChannels.push(null);
-    }
-  }
-
 }

+ 0 - 34
packages/app/src/server/util/middlewares.js

@@ -37,25 +37,6 @@ module.exports = (crowi) => {
   };
 
   middlewares.swigFilters = function(swig) {
-    // define a function for Gravatar
-    const generateGravatarSrc = function(user) {
-      const email = user.email || '';
-      const hash = md5(email.trim().toLowerCase());
-      return `https://gravatar.com/avatar/${hash}`;
-    };
-
-    // define a function for uploaded picture
-    const getUploadedPictureSrc = function(user) {
-      if (user.image) {
-        return user.image;
-      }
-      if (user.imageAttachment != null) {
-        return user.imageAttachment.filePathProxied;
-      }
-
-      return '/images/icons/user.svg';
-    };
-
 
     return function(req, res, next) {
       swig.setFilter('path2name', (string) => {
@@ -126,21 +107,6 @@ module.exports = (crowi) => {
           .replace(/\s(https?.+(jpe?g|png|gif))\s/, '\n\n\n![]($1)\n\n\n');
       });
 
-      swig.setFilter('gravatar', generateGravatarSrc);
-      swig.setFilter('uploadedpicture', getUploadedPictureSrc);
-
-      swig.setFilter('picture', (user) => {
-        if (!user) {
-          return '/images/icons/user.svg';
-        }
-
-        if (user.isGravatarEnabled === true) {
-          return generateGravatarSrc(user);
-        }
-
-        return getUploadedPictureSrc(user);
-      });
-
       swig.setFilter('encodeHTML', (string) => {
         return entities.encodeHTML(string);
       });

+ 0 - 1
packages/app/src/server/views/layout-growi/identical-path-page.html

@@ -10,7 +10,6 @@
     <div id="content-main" class="content-main d-flex"
       data-path="{{ encodeURI(path) }}"
       data-current-user="{% if user %}{{ user._id.toString() }}{% endif %}"
-      data-slack-channels="{% if page %}{{ page.slackChannels }}{% endif %}"
       data-page-is-not-creatable="true"
       data-page-is-deleted="{% if page.isDeleted() %}true{% else %}false{% endif %}"
       data-identical-path="true"

+ 0 - 1
packages/app/src/server/views/layout-growi/not_found.html

@@ -15,7 +15,6 @@
   </div>
   <div class="grw-container-convertible">
     {% include '../widget/page_alerts.html' %}
-    <div id="not-found-alert"></div>
   </div>
 {% endblock %}
 

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

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

+ 7 - 10
packages/app/src/stores/context.tsx

@@ -88,8 +88,8 @@ export const useShareLinksNumber = (initialData?: Nullable<any>): SWRResponse<Nu
   return useStaticSWR<Nullable<any>, Error>('shareLinksNumber', initialData);
 };
 
-export const useShareLinkId = (initialData?: Nullable<any>): SWRResponse<Nullable<any>, Error> => {
-  return useStaticSWR<Nullable<any>, Error>('shareLinkId', initialData);
+export const useShareLinkId = (initialData?: Nullable<string>): SWRResponse<Nullable<string>, Error> => {
+  return useStaticSWR<Nullable<string>, Error>('shareLinkId', initialData);
 };
 
 export const useRevisionIdHackmdSynced = (initialData?: Nullable<any>): SWRResponse<Nullable<any>, Error> => {
@@ -120,10 +120,6 @@ export const useRevisionAuthor = (initialData?: Nullable<any>): SWRResponse<Null
   return useStaticSWR<Nullable<any>, Error>('revisionAuthor', initialData);
 };
 
-export const useSlackChannels = (initialData?: Nullable<any>): SWRResponse<Nullable<any>, Error> => {
-  return useStaticSWR<Nullable<any>, Error>('slackChannels', initialData);
-};
-
 export const useIsSearchPage = (initialData?: Nullable<any>) : SWRResponse<Nullable<any>, Error> => {
   return useStaticSWR<Nullable<any>, Error>('isSearchPage', initialData);
 };
@@ -197,12 +193,13 @@ export const useIsEditable = (): SWRResponse<boolean, Error> => {
 
 export const useIsSharedUser = (): SWRResponse<boolean, Error> => {
   const { data: isGuestUser } = useIsGuestUser();
-  const { data: currentPagePath } = useCurrentPagePath();
+
+  const pathname = window.location.pathname;
 
   return useSWRImmutable(
-    ['isSharedUser', isGuestUser, currentPagePath],
-    (key: Key, isGuestUser: boolean, currentPagePath: string) => {
-      return isGuestUser && pagePathUtils.isSharedPage(currentPagePath as string);
+    ['isSharedUser', isGuestUser, pathname],
+    (key: Key, isGuestUser: boolean, pathname: string) => {
+      return isGuestUser && pagePathUtils.isSharedPage(pathname);
     },
   );
 };

+ 27 - 6
packages/app/src/stores/editor.tsx

@@ -1,17 +1,18 @@
-import { SWRResponse } from 'swr';
+import useSWR, { SWRResponse } from 'swr';
 import useSWRImmutable from 'swr/immutable';
 
+import { apiGet } from '~/client/util/apiv1-client';
 import { apiv3Get, apiv3Put } from '~/client/util/apiv3-client';
+import { Nullable } from '~/interfaces/common';
 import { IEditorSettings } from '~/interfaces/editor-settings';
+import { SlackChannels } from '~/interfaces/user-trigger-notification';
 
-import { useCurrentUser, useDefaultIndentSize, useIsGuestUser } from './context';
+import {
+  useCurrentUser, useDefaultIndentSize, useIsGuestUser,
+} from './context';
 import { localStorageMiddleware } from './middlewares/sync-to-storage';
 import { useStaticSWR } from './use-static-swr';
 
-export const useIsSlackEnabled = (isEnabled?: boolean): SWRResponse<boolean, Error> => {
-  return useStaticSWR('isSlackEnabled', isEnabled, { fallbackData: false });
-};
-
 
 type EditorSettingsOperation = {
   update: (updateData: Partial<IEditorSettings>) => void,
@@ -69,3 +70,23 @@ export const useCurrentIndentSize = (): SWRResponse<number, Error> => {
     { fallbackData: defaultIndentSize },
   );
 };
+
+/*
+* Slack Notification
+*/
+export const useSWRxSlackChannels = (currentPagePath: Nullable<string>): SWRResponse<string[], Error> => {
+  const shouldFetch: boolean = currentPagePath != null;
+  return useSWR(
+    shouldFetch ? ['/pages.updatePost', currentPagePath] : null,
+    (endpoint, path) => apiGet(endpoint, { path }).then((response: SlackChannels) => response.updatePost),
+    { fallbackData: [''] },
+  );
+};
+
+export const useIsSlackEnabled = (): SWRResponse<boolean, Error> => {
+  return useStaticSWR(
+    'isSlackEnabled',
+    undefined,
+    { fallbackData: false },
+  );
+};

+ 14 - 5
packages/app/src/stores/page.tsx

@@ -13,20 +13,29 @@ import { IPagingResult } from '~/interfaces/paging-result';
 import { apiGet } from '../client/util/apiv1-client';
 import { IPageTagsInfo } from '../interfaces/pageTagsInfo';
 
-import { useCurrentPagePath } from './context';
+import { useCurrentPageId, useCurrentPagePath } from './context';
 import { ITermNumberManagerUtil, useTermNumberManager } from './use-static-swr';
 
 
-export const useSWRxPageByPath = (path: string | null | undefined, initialData?: IPageHasId): SWRResponse<IPageHasId, Error> => {
+export const useSWRxPage = (pageId?: string, shareLinkId?: string): SWRResponse<IPageHasId, Error> => {
+  return useSWR(
+    pageId != null ? ['/page', pageId, shareLinkId] : null,
+    (endpoint, pageId, shareLinkId) => apiv3Get(endpoint, { pageId, shareLinkId }).then(result => result.data.page),
+  );
+};
+
+export const useSWRxPageByPath = (path?: string): SWRResponse<IPageHasId, Error> => {
   return useSWR(
     path != null ? ['/page', path] : null,
     (endpoint, path) => apiv3Get(endpoint, { path }).then(result => result.data.page),
-    {
-      fallbackData: initialData,
-    },
   );
 };
 
+export const useSWRxCurrentPage = (shareLinkId?: string): SWRResponse<IPageHasId, Error> => {
+  const { data: currentPageId } = useCurrentPageId();
+
+  return useSWRxPage(currentPageId ?? undefined, shareLinkId);
+};
 
 // eslint-disable-next-line @typescript-eslint/no-unused-vars
 export const useSWRxRecentlyUpdated = (): SWRResponse<(IPageHasId)[], Error> => {

+ 2 - 2
packages/app/src/stores/ui.tsx

@@ -287,8 +287,8 @@ export const useSidebarResizeDisabled = (isDisabled?: boolean): SWRResponse<bool
 };
 
 
-export const useSelectedGrant = (initialData?: Nullable<number>): SWRResponse<Nullable<number>, Error> => {
-  return useStaticSWR<Nullable<number>, Error>('grant', initialData);
+export const useSelectedGrant = (initialData?: number): SWRResponse<number, Error> => {
+  return useStaticSWR<number, Error>('grant', initialData);
 };
 
 export const useSelectedGrantGroupId = (initialData?: Nullable<string>): SWRResponse<Nullable<string>, Error> => {

Некоторые файлы не были показаны из-за большого количества измененных файлов