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

Merge branch 'support/apply-nextjs-2' into support/organize-app-packages

Taichi Masuyama 3 лет назад
Родитель
Сommit
d447192f8a
89 измененных файлов с 1733 добавлено и 1296 удалено
  1. 0 1
      packages/app/config/ci/.env.local.for-ci
  2. 3 1
      packages/app/package.json
  3. 3 0
      packages/app/public/static/locales/en_US/admin.json
  4. 14 2
      packages/app/public/static/locales/en_US/translation.json
  5. 3 0
      packages/app/public/static/locales/ja_JP/admin.json
  6. 14 2
      packages/app/public/static/locales/ja_JP/translation.json
  7. 3 0
      packages/app/public/static/locales/zh_CN/admin.json
  8. 14 2
      packages/app/public/static/locales/zh_CN/translation.json
  9. 8 14
      packages/app/resource/locales/en_US/sandbox-diagrams.md
  10. 1 1
      packages/app/resource/locales/en_US/sandbox-math.md
  11. 8 15
      packages/app/resource/locales/ja_JP/sandbox-diagrams.md
  12. 1 1
      packages/app/resource/locales/ja_JP/sandbox-math.md
  13. 8 14
      packages/app/resource/locales/zh_CN/sandbox-diagrams.md
  14. 1 1
      packages/app/resource/locales/zh_CN/sandbox-math.md
  15. 0 28
      packages/app/src/client/util/blink-section-header.ts
  16. 2 0
      packages/app/src/client/util/editor.ts
  17. 4 3
      packages/app/src/client/util/smooth-scroll.ts
  18. 2 2
      packages/app/src/components/Admin/App/AppSetting.jsx
  19. 17 10
      packages/app/src/components/Admin/Common/AdminNavigation.jsx
  20. 3 4
      packages/app/src/components/BookmarkButtons.module.scss
  21. 2 2
      packages/app/src/components/BookmarkButtons.tsx
  22. 1 1
      packages/app/src/components/ContentLinkButtons.module.scss
  23. 47 44
      packages/app/src/components/ContentLinkButtons.tsx
  24. 14 9
      packages/app/src/components/Fab.tsx
  25. 1 5
      packages/app/src/components/Icons/CreatePageIcon.tsx
  26. 1 6
      packages/app/src/components/Icons/ReturnTopIcon.tsx
  27. 0 217
      packages/app/src/components/InstallerForm.jsx
  28. 231 0
      packages/app/src/components/InstallerForm.tsx
  29. 3 3
      packages/app/src/components/Layout/BasicLayout.tsx
  30. 50 0
      packages/app/src/components/Layout/ShareLinkLayout.tsx
  31. 4 4
      packages/app/src/components/LikeButtons.module.scss
  32. 2 2
      packages/app/src/components/LikeButtons.tsx
  33. 174 144
      packages/app/src/components/LoginForm.tsx
  34. 0 1
      packages/app/src/components/Me/BasicInfoSettings.tsx
  35. 18 25
      packages/app/src/components/Navbar/GrowiContextualSubNavigation.tsx
  36. 4 5
      packages/app/src/components/Navbar/GrowiNavbar.tsx
  37. 16 19
      packages/app/src/components/Navbar/GrowiSubNavigation.tsx
  38. 3 13
      packages/app/src/components/Page.tsx
  39. 9 13
      packages/app/src/components/Page/DisplaySwitcher.tsx
  40. 0 5
      packages/app/src/components/Page/RevisionRenderer.tsx
  41. 0 52
      packages/app/src/components/Page/ShareLinkAlert.jsx
  42. 52 0
      packages/app/src/components/Page/ShareLinkAlert.tsx
  43. 62 65
      packages/app/src/components/PageAttachment.tsx
  44. 0 97
      packages/app/src/components/PageAttachment/DeleteAttachmentModal.jsx
  45. 98 0
      packages/app/src/components/PageAttachment/DeleteAttachmentModal.tsx
  46. 0 45
      packages/app/src/components/PageAttachment/PageAttachmentList.jsx
  47. 47 0
      packages/app/src/components/PageAttachment/PageAttachmentList.tsx
  48. 7 1
      packages/app/src/components/PageComment/CommentEditor.tsx
  49. 5 0
      packages/app/src/components/PageEditor/CodeMirrorEditor.module.scss
  50. 117 98
      packages/app/src/components/PageEditorByHackmd.tsx
  51. 22 1
      packages/app/src/components/ReactMarkdownComponents/Header.tsx
  52. 14 2
      packages/app/src/components/ReactMarkdownComponents/NextLink.tsx
  53. 2 5
      packages/app/src/components/SavePageControls.tsx
  54. 5 9
      packages/app/src/components/ShareLink/ShareLinkForm.tsx
  55. 4 1
      packages/app/src/components/TableOfContents.module.scss
  56. 2 11
      packages/app/src/components/TableOfContents.tsx
  57. 22 0
      packages/app/src/components/User/SeenUserInfo.module.scss
  58. 5 1
      packages/app/src/components/User/SeenUserInfo.tsx
  59. 4 9
      packages/app/src/components/User/UserInfo.tsx
  60. 2 4
      packages/app/src/interfaces/attachment.ts
  61. 1 0
      packages/app/src/interfaces/editor-settings.ts
  62. 11 0
      packages/app/src/interfaces/share-link.ts
  63. 2 1
      packages/app/src/pages/admin/[[...path]].page.tsx
  64. 26 6
      packages/app/src/pages/login.page.tsx
  65. 2 1
      packages/app/src/pages/me/[[...path]].page.tsx
  66. 169 0
      packages/app/src/pages/share/[[...path]].page.tsx
  67. 5 2
      packages/app/src/pages/tags.page.tsx
  68. 6 4
      packages/app/src/pages/utils/commons.ts
  69. 7 0
      packages/app/src/server/crowi/express-init.js
  70. 2 2
      packages/app/src/server/middlewares/register-form-validator.ts
  71. 15 1
      packages/app/src/server/routes/apiv3/index.js
  72. 76 0
      packages/app/src/server/routes/apiv3/installer.ts
  73. 3 6
      packages/app/src/server/routes/index.js
  74. 0 70
      packages/app/src/server/routes/installer.js
  75. 73 85
      packages/app/src/server/routes/login.js
  76. 0 1
      packages/app/src/server/service/app.ts
  77. 2 2
      packages/app/src/server/service/installer.ts
  78. 54 0
      packages/app/src/services/renderer/rehype-plugins/relocate-toc.ts
  79. 12 0
      packages/app/src/services/renderer/remark-plugins/plantuml.ts
  80. 9 29
      packages/app/src/services/renderer/renderer.tsx
  81. 13 9
      packages/app/src/stores/attachment.tsx
  82. 6 7
      packages/app/src/stores/ui.tsx
  83. 0 17
      packages/app/src/styles/atoms/_buttons.scss
  84. 9 0
      packages/app/src/styles/theme/_apply-colors-dark.scss
  85. 9 0
      packages/app/src/styles/theme/_apply-colors-light.scss
  86. 1 1
      packages/app/src/styles/theme/_apply-colors.scss
  87. 1 0
      packages/core/src/interfaces/user.ts
  88. 3 1
      packages/ui/src/components/Attachment/Attachment.jsx
  89. 57 31
      yarn.lock

+ 0 - 1
packages/app/config/ci/.env.local.for-ci

@@ -1,2 +1 @@
 FORMAT_NODE_LOG=true
-MATHJAX=1

+ 3 - 1
packages/app/package.json

@@ -56,6 +56,7 @@
     "string-width": "5.0.0 or above exports only ESM."
   },
   "dependencies": {
+    "@akebifiky/remark-simple-plantuml": "^1.0.2",
     "@aws-sdk/client-s3": "^3.58.0",
     "@aws-sdk/s3-request-presigner": "^3.58.0",
     "@browser-bunyan/console-formatted-stream": "^1.8.0",
@@ -129,7 +130,7 @@
     "multer": "~1.4.0",
     "multer-autoreap": "^1.0.3",
     "next": "^12.2.5",
-    "next-i18next": "^11.0.0",
+    "next-i18next": "^11.3.0",
     "next-superjson": "^0.0.4",
     "next-themes": "^0.2.0",
     "nocache": "^3.0.1",
@@ -251,6 +252,7 @@
     "react-dropzone": "^11.2.4",
     "react-frame-component": "^4.0.0",
     "react-hotkeys": "^2.0.0",
+    "react-scroll": "^1.8.7",
     "react-use-ripple": "^1.5.2",
     "react-waypoint": "^10.1.0",
     "reactstrap": "^8.9.0",

+ 3 - 0
packages/app/public/static/locales/en_US/admin.json

@@ -1,4 +1,7 @@
 {
+  "meta": {
+    "display_name": "English"
+  },
   "wiki_management_home_page": "Wiki Management Home Page",
   "app_settings": "App Settings",
   "security_settings": {

+ 14 - 2
packages/app/public/static/locales/en_US/translation.json

@@ -191,7 +191,9 @@
     "setup": "Setup",
     "create_initial_account": "Create an initial account",
     "initial_account_will_be_administrator_automatically": "The initial account will be administrator automatically.",
-    "unavaliable_user_id": "This 'User ID' is unavailable."
+    "unavaliable_user_id": "This 'User ID' is unavailable.",
+    "failed_to_install": "Failed to install GROWI. Please try again.",
+    "failed_to_login_after_install": "Failed to login after installation. Redirecting to the login form ..."
   },
   "breaking_changes": {
     "v346_using_basic_auth": "Basic Authentication currently in use will <strong>no longer be available</strong> in the near future. Remove settings from %s"
@@ -709,7 +711,17 @@
     "complete_to_install2":"Complete to Install GROWI ! Please check each settings on this page first.",
     "failed_to_create_admin_user":"Failed to create admin user. {{errMessage}}",
     "successfully_send_email_auth":"We sent an email to {{email}}. Please click the URL in the email and complete the registration.",
-    "incorrect_token_or_expired_url": "The token is incorrect or the URL has expired."
+    "incorrect_token_or_expired_url": "The token is incorrect or the URL has expired.",
+    "user_already_loggedin": "You cannot create a new account when you are logged in.",
+    "registration_closed": "You are not authorized to create a new account.",
+    "Username has invalid characters": "Username has invalid characters.",
+    "Username field is required": "User ID field is required",
+    "Name field is required": "Name field is required",
+    "Email format is invalid": "Email format is invalid",
+    "Email field is required": "Email field is required",
+    "Password has invalid character": "Password has invalid character",
+    "Password minimum character should be more than 8 characters": "Password minimum character should be more than 8 characters",
+    "Password field is required": "Password field is required"
   },
   "grid_edit":{
     "create_bootstrap_4_grid":"Create Bootstrap 4 Grid",

+ 3 - 0
packages/app/public/static/locales/ja_JP/admin.json

@@ -1,4 +1,7 @@
 {
+  "meta": {
+    "display_name": "日本語"
+  },
   "Update": "更新",
   "Delete": "削除",
   "User": "ユーザー",

+ 14 - 2
packages/app/public/static/locales/ja_JP/translation.json

@@ -184,7 +184,9 @@
     "setup": "セットアップ",
     "create_initial_account": "最初のアカウントの作成",
     "initial_account_will_be_administrator_automatically": "初めに作成するアカウントは、自動的に管理者権限が付与されます",
-    "unavaliable_user_id": "このユーザーIDは利用できません。"
+    "unavaliable_user_id": "このユーザーIDは利用できません。",
+    "failed_to_install": "GROWI のインストールに失敗しました。再度お試しください。",
+    "failed_to_login_after_install": "インストール後、ログインに失敗しました。ログインフォームに遷移しています ..."
   },
   "breaking_changes": {
     "v346_using_basic_auth": "現在利用中の Basic 認証機能は、近い将来<strong>廃止されます</strong>。%s から設定を削除してください。"
@@ -700,7 +702,17 @@
     "complete_to_install2":"GROWI のインストールが完了しました!はじめに、このページで各種設定を確認してください。",
     "failed_to_create_admin_user":"管理ユーザーの作成に失敗しました。{{errMessage}}",
     "successfully_send_email_auth":"{{email}} にメールを送信しました。添付されたURLをクリックし、本登録を完了させてください",
-    "incorrect_token_or_expired_url":"トークンが正しくないか、URLの有効期限が切れています。"
+    "incorrect_token_or_expired_url":"トークンが正しくないか、URLの有効期限が切れています。",
+    "user_already_loggedin": "ログイン中のため、新規アカウントを作成できませんでした。",
+    "registration_closed": "新しいアカウントを作成する権限がありません。",
+    "Username has invalid characters": "ユーザー名に不正な文字が含まれています.",
+    "Username field is required": "User ID は必須項目です",
+    "Name field is required": "ユーザーID は必須項目です",
+    "Email format is invalid": "メールアドレスのフォーマットが無効です",
+    "Email field is required": "メールアドレスは必須項目です",
+    "Password has invalid character": "パスワードに無効な文字があります",
+    "Password minimum character should be more than 8 characters": "パスワードの最小文字数は8文字以上です",
+    "Password field is required": "パスワードの欄は必ず入力してください"
   },
   "grid_edit":{
     "create_bootstrap_4_grid":"Bootstrap 4 グリッドを作成",

+ 3 - 0
packages/app/public/static/locales/zh_CN/admin.json

@@ -1,4 +1,7 @@
 {
+  "meta": {
+    "display_name": "简体中文"
+  },
   "Update": "更新",
   "Delete": "删除",
   "User": "用户",

+ 14 - 2
packages/app/public/static/locales/zh_CN/translation.json

@@ -186,7 +186,9 @@
 		"setup": "安装",
 		"create_initial_account": "创建初始用户",
 		"initial_account_will_be_administrator_automatically": "初始帐户将自动成为管理员。",
-		"unavaliable_user_id": "用户ID不可用"
+		"unavaliable_user_id": "用户ID不可用",
+    "failed_to_install": "GROWI安装失败。请再试一次。",
+    "failed_to_login_after_install": "安装后登录失败。重定向到登录表格..."
 	},
 	"breaking_changes": {
 		"v346_using_basic_auth": "当前使用的基本身份验证在不久的将来将不再可用。从%s中删除设置"
@@ -756,7 +758,17 @@
 		"complete_to_install2": "完成安装GROWI!请先检查此页上的每个设置。",
 		"failed_to_create_admin_user": "无法创建管理用户。{{errMessage}",
     "successfully_send_email_auth":"我们向 {{email}} 发送了一封电子邮件。 请点击邮件中的网址并完成注册。",
-    "incorrect_token_or_expired_url":"令牌不正确或 URL 已过期。"
+    "incorrect_token_or_expired_url":"令牌不正确或 URL 已过期。",
+    "user_already_loggedin": "当你登录的时候,你不能创建一个新的账户。",
+    "registration_closed": "你无权创建一个新的账户。",
+    "Username has invalid characters": "用户名有无效字符",
+    "Username field is required": "用户ID字段是必需的",
+    "Name field is required": "姓名字段为必填项",
+    "Email format is invalid": "电子邮件的格式是无效的",
+    "Email field is required": "电子邮件字段是必需的",
+    "Password has invalid character": "密码有无效字符",
+    "Password minimum character should be more than 8 characters": "密码最小字符应超过8个字符",
+    "Password field is required": "密码字段是必需的"
 	},
   "grid_edit":{
     "create_bootstrap_4_grid":"创建Bootstrap 4网格",

+ 8 - 14
packages/app/resource/locales/en_US/sandbox-diagrams.md

@@ -29,6 +29,7 @@ See [PlantUML](http://plantuml.com/).
 
 ## Sequence diagram
 
+``` plantuml
 @startuml
 skinparam sequenceArrowThickness 2
 skinparam roundcorner 20
@@ -58,13 +59,12 @@ A --> User: Done
 deactivate A
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## Class diagram
 
+``` plantuml
 @startuml
 
 class BaseClass
@@ -86,13 +86,11 @@ namespace net.foo {
 BaseClass <|-- net.unused.Person
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## Component diagram
-
+``` plantuml
 @startuml
 
 package "Some Group" {
@@ -125,14 +123,12 @@ database "MySql" {
 [Folder 3] --> [Frame 4]
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## State diagram
 
-
+``` plantuml
 @startuml
 scale 600 width
 
@@ -153,9 +149,7 @@ State3 --> [*] : Succeeded / Save Result
 State3 --> [*] : Aborted
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 # :pencil: blockdiag

+ 1 - 1
packages/app/resource/locales/en_US/sandbox-math.md

@@ -1,6 +1,6 @@
 # :pencil: Math
 
-See [MathJax](https://www.mathjax.org/).
+See [KaTeX](https://katex.org/).
 
 ## Inline Formula
 

+ 8 - 15
packages/app/resource/locales/ja_JP/sandbox-diagrams.md

@@ -28,7 +28,7 @@ See [diagrams.net](https://diagrams.net)
 See [PlantUML](http://plantuml.com/).
 
 ## シーケンス図
-
+``` plantuml
 @startuml
 skinparam sequenceArrowThickness 2
 skinparam roundcorner 20
@@ -58,13 +58,11 @@ A --> User: Done
 deactivate A
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## クラス図
-
+``` plantuml
 @startuml
 
 class BaseClass
@@ -86,13 +84,11 @@ namespace net.foo {
 BaseClass <|-- net.unused.Person
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## コンポーネント図
-
+``` plantuml
 @startuml
 
 package "Some Group" {
@@ -125,14 +121,12 @@ database "MySql" {
 [Folder 3] --> [Frame 4]
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## ステート図
 
-
+``` plantuml
 @startuml
 scale 600 width
 
@@ -153,9 +147,8 @@ State3 --> [*] : Succeeded / Save Result
 State3 --> [*] : Aborted
 
 @enduml
+```
 
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
 
 # :pencil: blockdiag
 

+ 1 - 1
packages/app/resource/locales/ja_JP/sandbox-math.md

@@ -1,6 +1,6 @@
 # :pencil: Math
 
-See [MathJax](https://www.mathjax.org/).
+See [KaTeX](https://katex.org/).
 
 ## Inline Formula
 

+ 8 - 14
packages/app/resource/locales/zh_CN/sandbox-diagrams.md

@@ -29,6 +29,7 @@ See [PlantUML](http://plantuml.com/).
 
 ## Sequence diagram
 
+``` plantuml
 @startuml
 skinparam sequenceArrowThickness 2
 skinparam roundcorner 20
@@ -58,13 +59,12 @@ A --> User: Done
 deactivate A
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## Class diagram
 
+``` plantuml
 @startuml
 
 class BaseClass
@@ -86,13 +86,11 @@ namespace net.foo {
 BaseClass <|-- net.unused.Person
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## Component diagram
-
+``` plantuml
 @startuml
 
 package "Some Group" {
@@ -125,14 +123,12 @@ database "MySql" {
 [Folder 3] --> [Frame 4]
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 ## State diagram
 
-
+``` plantuml
 @startuml
 scale 600 width
 
@@ -153,9 +149,7 @@ State3 --> [*] : Succeeded / Save Result
 State3 --> [*] : Aborted
 
 @enduml
-
-<!-- Reset PlantUML -->
-<div class="clearfix"></div>
+```
 
 
 # :pencil: blockdiag

+ 1 - 1
packages/app/resource/locales/zh_CN/sandbox-math.md

@@ -1,6 +1,6 @@
 # :pencil: Math
 
-See [MathJax](https://www.mathjax.org/).
+See [KaTeX](https://katex.org/).
 
 ## Inline Formula
 

+ 0 - 28
packages/app/src/client/util/blink-section-header.ts

@@ -1,28 +0,0 @@
-let lastBlinkedElem;
-
-export const blinkElem = (elem: HTMLElement): void => {
-  if (lastBlinkedElem != null) {
-    lastBlinkedElem.classList.remove('blink');
-  }
-
-  elem.classList.add('blink');
-  lastBlinkedElem = elem;
-};
-
-export const blinkSectionHeaderAtBoot = (): HTMLElement | undefined => {
-  const { hash } = window.location;
-
-  if (hash.length === 0) {
-    return;
-  }
-
-  // omit '#'
-  const id = hash.replace('#', '');
-  // don't use jQuery and document.querySelector
-  //  because hash may containe Base64 encoded strings
-  const elem = document.getElementById(id);
-  if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
-    blinkElem(elem);
-    return elem;
-  }
-};

+ 2 - 0
packages/app/src/client/util/editor.ts

@@ -7,6 +7,7 @@ export const getOptionsToSave = (
     grantUserGroupId: string | null | undefined,
     grantUserGroupName: string | null | undefined,
     pageTags: string[],
+    isSyncRevisionToHackmd?: boolean,
 ): OptionsToSave => {
   return {
     pageTags,
@@ -15,5 +16,6 @@ export const getOptionsToSave = (
     grant,
     grantUserGroupId,
     grantUserGroupName,
+    isSyncRevisionToHackmd,
   };
 };

+ 4 - 3
packages/app/src/client/util/smooth-scroll.ts

@@ -1,10 +1,11 @@
 const WIKI_HEADER_LINK = 120;
 
-export const smoothScrollIntoView = (element: HTMLElement, offsetTop = 0, scrollElement: HTMLElement | Window = window): void => {
-  const targetElement = element || window.document.body;
+export const smoothScrollIntoView = (
+    element: HTMLElement = window.document.body, offsetTop = 0, scrollElement: HTMLElement | Window = window,
+): void => {
 
   // get the distance to the target element top
-  const rectTop = targetElement.getBoundingClientRect().top;
+  const rectTop = element.getBoundingClientRect().top;
 
   const top = window.pageYOffset + rectTop - offsetTop;
 

+ 2 - 2
packages/app/src/components/Admin/App/AppSetting.jsx

@@ -79,8 +79,8 @@ const AppSetting = (props) => {
         <div className="col-md-6 py-2">
           {
             i18nConfig.locales.map((locale) => {
-              const fixedT = i18n.getFixedT(locale);
-              i18n.loadLanguages(i18nConfig.locales);
+              if (i18n == null) { return }
+              const fixedT = i18n.getFixedT(locale, 'admin');
 
               return (
                 <div key={locale} className="custom-control custom-radio custom-control-inline">

+ 17 - 10
packages/app/src/components/Admin/Common/AdminNavigation.jsx

@@ -1,11 +1,8 @@
-/* eslint-disable no-multi-spaces */
-/* eslint-disable react/jsx-props-no-multi-spaces */
-
-
 import React from 'react';
 
 import { pathUtils } from '@growi/core';
 import { useTranslation } from 'next-i18next';
+import Link from 'next/link';
 import PropTypes from 'prop-types';
 import urljoin from 'url-join';
 
@@ -25,6 +22,7 @@ const AdminNavigation = (props) => {
   // eslint-disable-next-line react/prop-types
   const MenuLabel = ({ menu }) => {
     switch (menu) {
+      /* eslint-disable no-multi-spaces */
       case 'app':                      return <><i className="icon-fw icon-settings"></i>        { t('app_settings') }</>;
       case 'security':                 return <><i className="icon-fw icon-shield"></i>          { t('security_settings.security_settings') }</>;
       case 'markdown':                 return <><i className="icon-fw icon-note"></i>            { t('markdown_settings.markdown_settings') }</>;
@@ -42,6 +40,7 @@ const AdminNavigation = (props) => {
       case 'audit-log':                return <><i className="icon-fw icon-feed"></i>            { t('audit_log_management.audit_log')}</>;
       case 'cloud':                    return <><i className="icon-fw icon-share-alt"></i>       { t('to_cloud_settings')} </>;
       default:                         return <><i className="icon-fw icon-home"></i>            { t('wiki_management_home_page') }</>;
+      /* eslint-enable no-multi-spaces */
     }
   };
 
@@ -53,13 +52,17 @@ const AdminNavigation = (props) => {
       ? 'list-group-item list-group-item-action border-0 round-corner'
       : 'dropdown-item px-3 py-2';
 
+    const href = isRoot ? '/admin' : urljoin('/admin', menu);
+
     return (
-      <a
-        href={isRoot ? '/admin' : urljoin('/admin', menu)}
-        className={`${pageTransitionClassName} ${isActive ? 'active' : ''}`}
-      >
-        <MenuLabel menu={menu} />
-      </a>
+      <Link href={href}>
+        <a
+          href={href}
+          className={`${pageTransitionClassName} ${isActive ? 'active' : ''}`}
+        >
+          <MenuLabel menu={menu} />
+        </a>
+      </Link>
     );
   };
 
@@ -76,6 +79,7 @@ const AdminNavigation = (props) => {
   const getListGroupItemOrDropdownItemList = (isListGroupItems) => {
     return (
       <>
+        {/* eslint-disable no-multi-spaces */}
         <MenuLink menu="home"         isListGroupItems isActive={pathname === '/admin'} isRoot />
         <MenuLink menu="app"          isListGroupItems isActive={isActiveMenu('/app')} />
         <MenuLink menu="security"     isListGroupItems isActive={isActiveMenu('/security')} />
@@ -100,6 +104,7 @@ const AdminNavigation = (props) => {
             </a>
           )
         } */}
+        {/* eslint-enable no-multi-spaces */}
       </>
     );
   };
@@ -123,6 +128,7 @@ const AdminNavigation = (props) => {
           aria-expanded="false"
         >
           <span className="float-left">
+            {/* eslint-disable no-multi-spaces */}
             {pathname === '/admin' &&              <MenuLabel menu="home" />}
             {isActiveMenu('/app') &&               <MenuLabel menu="app" />}
             {isActiveMenu('/security') &&          <MenuLabel menu="security" />}
@@ -136,6 +142,7 @@ const AdminNavigation = (props) => {
             {isActiveMenu('/user-groups') &&       <MenuLabel menu="user-groups" />}
             {isActiveMenu('/search') &&            <MenuLabel menu="search" />}
             {isActiveMenu('/audit-log') &&         <MenuLabel menu="audit-log" />}
+            {/* eslint-enable no-multi-spaces */}
           </span>
         </button>
         <div className="dropdown-menu" aria-labelledby="dropdown-admin-navigation">

+ 3 - 4
packages/app/src/components/BookmarkButtons.module.scss

@@ -1,12 +1,11 @@
 @use '~/styles/bootstrap/init' as bs;
 
-.btn-bookmark {
-  :global {
+.btn-group-bookmark :global {
+  .btn-bookmark {
     box-shadow: none !important;
-  }
 
-  &:global {
     @include bs.button-outline-variant(rgba(bs.$secondary, 50%), bs.$orange, rgba(lighten(bs.$orange, 20%), 0.5), rgba(lighten(bs.$orange, 20%), 0.5));
+
     &:not(:disabled):not(.disabled):active,
     &:not(:disabled):not(.disabled).active {
       color: bs.$orange;

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

@@ -52,12 +52,12 @@ const BookmarkButtons: FC<Props> = (props: Props) => {
   }, [isGuestUser, isBookmarked]);
 
   return (
-    <div className="btn-group" role="group" aria-label="Bookmark buttons">
+    <div className={`btn-group btn-group-bookmark ${styles['btn-group-bookmark']}`} role="group" aria-label="Bookmark buttons">
       <button
         type="button"
         id="bookmark-button"
         onClick={handleClick}
-        className={`shadow-none btn btn-bookmark ${styles['btn-bookmark']} border-0
+        className={`shadow-none btn btn-bookmark border-0
           ${isBookmarked ? 'active' : ''} ${isGuestUser ? 'disabled' : ''}`}
       >
         <i className={`fa ${isBookmarked ? 'fa-bookmark' : 'fa-bookmark-o'}`}></i>

+ 1 - 1
packages/app/src/styles/_toc.scss → packages/app/src/components/ContentLinkButtons.module.scss

@@ -1,4 +1,4 @@
-.grw-icon-container-recently-created {
+.grw-icon-container-recently-created :global {
   svg {
     width: 14px;
     height: 14px;

+ 47 - 44
packages/app/src/components/ContentLinkButtons.tsx

@@ -1,57 +1,62 @@
-import React, { useCallback, useMemo } from 'react';
+import React, { useCallback } from 'react';
 
 import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
 import { RecentlyCreatedIcon } from '~/components/Icons/RecentlyCreatedIcon';
 import { usePageUser } from '~/stores/context';
 
+import styles from './ContentLinkButtons.module.scss';
 
 const WIKI_HEADER_LINK = 120;
 
+const BookMarkLinkButton = React.memo(() => {
 
-const ContentLinkButtons = (): JSX.Element => {
+  const BookMarkLinkButtonClickHandler = useCallback(() => {
+    const getBookMarkListHeaderDom = document.getElementById('bookmarks-list');
+    if (getBookMarkListHeaderDom == null) { return }
+    smoothScrollIntoView(getBookMarkListHeaderDom, WIKI_HEADER_LINK);
+  }, []);
+
+  return (
+    <button
+      type="button"
+      className="btn btn-outline-secondary btn-sm px-2"
+      onClick={BookMarkLinkButtonClickHandler}
+    >
+      <i className="fa fa-fw fa-bookmark-o"></i>
+      <span>Bookmarks</span>
+    </button>
+  );
+});
+
+BookMarkLinkButton.displayName = 'BookMarkLinkButton';
+
+const RecentlyCreatedLinkButton = React.memo(() => {
+
+  const RecentlyCreatedListButtonClickHandler = useCallback(() => {
+    const getRecentlyCreatedListHeaderDom = document.getElementById('recently-created-list');
+    if (getRecentlyCreatedListHeaderDom == null) { return }
+    smoothScrollIntoView(getRecentlyCreatedListHeaderDom, WIKI_HEADER_LINK);
+  }, []);
+
+  return (
+    <button
+      type="button"
+      className="btn btn-outline-secondary btn-sm px-3"
+      onClick={RecentlyCreatedListButtonClickHandler}
+    >
+      <i className={`${styles['grw-icon-container-recently-created']} grw-icon-container-recently-created mr-2`}><RecentlyCreatedIcon /></i>
+      <span>Recently Created</span>
+    </button>
+  );
+});
+
+RecentlyCreatedLinkButton.displayName = 'RecentlyCreatedLinkButton';
+
+export const ContentLinkButtons = (): JSX.Element => {
 
   const { data: pageUser } = usePageUser();
 
-  // get element for smoothScroll
-  const getBookMarkListHeaderDom = useMemo(() => { return document.getElementById('bookmarks-list') }, []);
-  const getRecentlyCreatedListHeaderDom = useMemo(() => { return document.getElementById('recently-created-list') }, []);
-
-
-  const BookMarkLinkButton = useCallback((): JSX.Element => {
-    if (getBookMarkListHeaderDom == null) {
-      return <></>;
-    }
-
-    return (
-      <button
-        type="button"
-        className="btn btn-outline-secondary btn-sm px-2"
-        onClick={() => smoothScrollIntoView(getBookMarkListHeaderDom, WIKI_HEADER_LINK)}
-      >
-        <i className="fa fa-fw fa-bookmark-o"></i>
-        <span>Bookmarks</span>
-      </button>
-    );
-  }, [getBookMarkListHeaderDom]);
-
-  const RecentlyCreatedLinkButton = useCallback(() => {
-    if (getRecentlyCreatedListHeaderDom == null) {
-      return <></>;
-    }
-
-    return (
-      <button
-        type="button"
-        className="btn btn-outline-secondary btn-sm px-3"
-        onClick={() => smoothScrollIntoView(getRecentlyCreatedListHeaderDom, WIKI_HEADER_LINK)}
-      >
-        <i className="grw-icon-container-recently-created mr-2"><RecentlyCreatedIcon /></i>
-        <span>Recently Created</span>
-      </button>
-    );
-  }, [getRecentlyCreatedListHeaderDom]);
-
-  if (pageUser == null) {
+  if (pageUser == null || pageUser.status === 4) {
     return <></>;
   }
 
@@ -63,5 +68,3 @@ const ContentLinkButtons = (): JSX.Element => {
   );
 
 };
-
-export default ContentLinkButtons;

+ 14 - 9
packages/app/src/components/Fab.jsx → packages/app/src/components/Fab.tsx

@@ -10,18 +10,18 @@ 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 { CreatePageIcon } from './Icons/CreatePageIcon';
+import { ReturnTopIcon } from './Icons/ReturnTopIcon';
 
 import styles from './Fab.module.scss';
 
 const logger = loggerFactory('growi:cli:Fab');
 
-const Fab = () => {
-  const { data: currentUser } = useCurrentUser();
+export const Fab = (): JSX.Element => {
 
-  const { open: openCreateModal } = usePageCreateModal();
+  const { data: currentUser } = useCurrentUser();
   const { data: currentPath = '' } = useCurrentPagePath();
+  const { open: openCreateModal } = usePageCreateModal();
 
   const [animateClasses, setAnimateClasses] = useState('invisible');
   const [buttonClasses, setButtonClasses] = useState('');
@@ -30,6 +30,9 @@ const Fab = () => {
   const createBtnRef = useRef(null);
   useRipple(createBtnRef, { rippleColor: 'rgba(255, 255, 255, 0.3)' });
 
+  /*
+  * Comment out to prevent err >>> TypeError: Cannot read properties of null (reading 'bottom')
+  */
   const stickyChangeHandler = useCallback((event) => {
     logger.debug('StickyEvents.CHANGE detected');
 
@@ -55,7 +58,11 @@ const Fab = () => {
     };
   }, [stickyChangeHandler]);
 
-  function renderPageCreateButton() {
+  if (currentPath == null) {
+    return <></>;
+  }
+
+  const renderPageCreateButton = () => {
     return (
       <>
         <div className={`rounded-circle position-absolute ${animateClasses}`} style={{ bottom: '2.3rem', right: '4rem' }}>
@@ -70,7 +77,7 @@ const Fab = () => {
         </div>
       </>
     );
-  }
+  };
 
   return (
     <div className={`${styles['grw-fab']} grw-fab d-none d-md-block d-edit-none`} data-testid="grw-fab">
@@ -88,5 +95,3 @@ const Fab = () => {
   );
 
 };
-
-export default Fab;

+ 1 - 5
packages/app/src/components/Icons/CreatePageIcon.jsx → packages/app/src/components/Icons/CreatePageIcon.tsx

@@ -1,6 +1,6 @@
 import React from 'react';
 
-const CreatePageIcon = () => (
+export const CreatePageIcon = (): JSX.Element => (
   <svg
     xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 27 30"
@@ -19,8 +19,4 @@ const CreatePageIcon = () => (
     />
     <rect fillOpacity="0" width="27" height="27" />
   </svg>
-
 );
-
-
-export default CreatePageIcon;

+ 1 - 6
packages/app/src/components/Icons/ReturnTopIcon.jsx → packages/app/src/components/Icons/ReturnTopIcon.tsx

@@ -1,6 +1,6 @@
 import React from 'react';
 
-const ReturnTopIcon = () => (
+export const ReturnTopIcon = (): JSX.Element => (
   <svg
     xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 23 23"
@@ -11,10 +11,5 @@ const ReturnTopIcon = () => (
     />
     <path d="M22.35,4.61H.65a.65.65,0,0,1,0-1.3h21.7a.65.65,0,1,1,0,1.3Z" />
     <rect fillOpacity="0" width="23" height="23" />
-
   </svg>
-
 );
-
-
-export default ReturnTopIcon;

+ 0 - 217
packages/app/src/components/InstallerForm.jsx

@@ -1,217 +0,0 @@
-import React from 'react';
-
-import i18next from 'i18next';
-import { useTranslation, i18n } from 'next-i18next';
-import PropTypes from 'prop-types';
-
-import { i18n as i18nConfig } from '^/config/next-i18next.config';
-
-import { useCsrfToken } from '~/stores/context';
-
-class InstallerForm extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      isValidUserName: true,
-      isSubmittingDisabled: false,
-    };
-    this.checkUserName = this.checkUserName.bind(this);
-
-    this.submitHandler = this.submitHandler.bind(this);
-  }
-
-  checkUserName(event) {
-    const axios = require('axios').create({
-      headers: {
-        'Content-Type': 'application/json',
-        'X-Requested-With': 'XMLHttpRequest',
-      },
-      responseType: 'json',
-    });
-    axios.get('/_api/v3/check-username', { params: { username: event.target.value } })
-      .then((res) => { return this.setState({ isValidUserName: res.data.valid }) });
-  }
-
-  submitHandler() {
-    if (this.state.isSubmittingDisabled) {
-      return;
-    }
-
-    this.setState({ isSubmittingDisabled: true });
-    setTimeout(() => {
-      this.setState({ isSubmittingDisabled: false });
-    }, 3000);
-  }
-
-  render() {
-    const { t } = this.props;
-    const hasErrorClass = this.state.isValidUserName ? '' : ' has-error';
-    const unavailableUserId = this.state.isValidUserName
-      ? ''
-      : <span><i className="icon-fw icon-ban" />{ this.props.t('installer.unavaliable_user_id') }</span>;
-
-    return (
-      <div data-testid="installerForm" className={`noLogin-dialog p-3 mx-auto${hasErrorClass}`}>
-        <div className="row">
-          <div className="col-md-12">
-            <p className="alert alert-success">
-              <strong>{ this.props.t('installer.create_initial_account') }</strong><br />
-              <small>{ this.props.t('installer.initial_account_will_be_administrator_automatically') }</small>
-            </p>
-          </div>
-        </div>
-        <div className="row">
-          <form role="form" action="/installer" method="post" id="register-form" className="col-md-12" onSubmit={this.submitHandler}>
-            <div className="dropdown mb-3">
-              <div className="d-flex dropdown-with-icon">
-                <i className="icon-bubbles border-0 rounded-0" />
-                <button
-                  type="button"
-                  className="btn btn-secondary dropdown-toggle text-right w-100 border-0 shadow-none"
-                  id="dropdownLanguage"
-                  data-testid="dropdownLanguage"
-                  data-toggle="dropdown"
-                  aria-haspopup="true"
-                  aria-expanded="true"
-                >
-                  <span className="float-left">
-                    {t('meta.display_name')}
-                  </span>
-                </button>
-                <input
-                  type="hidden"
-                  name="registerForm[app:globalLang]"
-                />
-                <div className="dropdown-menu" aria-labelledby="dropdownLanguage">
-                  {
-                    i18nConfig.locales.map((locale) => {
-                      const fixedT = i18n.getFixedT(locale);
-                      i18n.loadLanguages(i18nConfig.locales);
-
-                      return (
-                        <button
-                          key={locale}
-                          data-testid={`dropdownLanguageMenu-${locale}`}
-                          className="dropdown-item"
-                          type="button"
-                          onClick={() => { i18next.changeLanguage(locale) }}
-                        >
-                          {fixedT('meta.display_name')}
-                        </button>
-                      );
-                    })
-                  }
-                </div>
-              </div>
-            </div>
-
-            <div className={`input-group mb-3${hasErrorClass}`}>
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-user" /></span>
-              </div>
-              <input
-                data-testid="tiUsername"
-                type="text"
-                className="form-control"
-                placeholder={this.props.t('User ID')}
-                name="registerForm[username]"
-                defaultValue={this.props.userName}
-                // onBlur={this.checkUserName} // need not to check username before installation -- 2020.07.24 Yuki Takei
-                required
-              />
-            </div>
-            <p className="form-text">{ unavailableUserId }</p>
-
-            <div className="input-group mb-3">
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-tag" /></span>
-              </div>
-              <input
-                data-testid="tiName"
-                type="text"
-                className="form-control"
-                placeholder={this.props.t('Name')}
-                name="registerForm[name]"
-                defaultValue={this.props.name}
-                required
-              />
-            </div>
-
-            <div className="input-group mb-3">
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-envelope" /></span>
-              </div>
-              <input
-                data-testid="tiEmail"
-                type="email"
-                className="form-control"
-                placeholder={this.props.t('Email')}
-                name="registerForm[email]"
-                defaultValue={this.props.email}
-                required
-              />
-            </div>
-
-            <div className="input-group mb-3">
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-lock" /></span>
-              </div>
-              <input
-                data-testid="tiPassword"
-                type="password"
-                className="form-control"
-                placeholder={this.props.t('Password')}
-                name="registerForm[password]"
-                required
-              />
-            </div>
-
-            <input type="hidden" name="_csrf" value={this.props.csrfToken} />
-
-            <div className="input-group mt-4 mb-3 d-flex justify-content-center">
-              <button
-                data-testid="btnSubmit"
-                type="submit"
-                className="btn-fill btn btn-register"
-                id="register"
-                disabled={this.state.isSubmittingDisabled}
-              >
-                <div className="eff"></div>
-                <span className="btn-label"><i className="icon-user-follow" /></span>
-                <span className="btn-label-text">{ this.props.t('Create') }</span>
-              </button>
-            </div>
-
-            <div className="input-group mt-4 d-flex justify-content-center">
-              <a href="https://growi.org" className="link-growi-org">
-                <span className="growi">GROWI</span>.<span className="org">ORG</span>
-              </a>
-            </div>
-          </form>
-        </div>
-      </div>
-    );
-  }
-
-}
-
-InstallerForm.propTypes = {
-  // i18next
-  t: PropTypes.func.isRequired,
-  // for input value
-  userName: PropTypes.string,
-  name: PropTypes.string,
-  email: PropTypes.string,
-  csrfToken: PropTypes.string,
-};
-
-const InstallerFormWrapperFC = (props) => {
-  const { t } = useTranslation();
-  const { data: csrfToken } = useCsrfToken();
-
-  return <InstallerForm t={t} csrfToken={csrfToken} {...props} />;
-};
-
-export default InstallerFormWrapperFC;

+ 231 - 0
packages/app/src/components/InstallerForm.tsx

@@ -0,0 +1,231 @@
+import {
+  FormEventHandler, memo, useCallback, useState,
+} from 'react';
+
+import i18next from 'i18next';
+import { useTranslation, i18n } from 'next-i18next';
+
+import { i18n as i18nConfig } from '^/config/next-i18next.config';
+
+import { toastError } from '~/client/util/apiNotification';
+import { apiv3Post } from '~/client/util/apiv3-client';
+
+const InstallerForm = memo((): JSX.Element => {
+  const { t } = useTranslation();
+
+  const [isValidUserName, setValidUserName] = useState(true);
+  const [isSubmittingDisabled, setSubmittingDisabled] = useState(false);
+
+  const checkUserName = useCallback(async(event) => {
+    const axios = require('axios').create({
+      headers: {
+        'Content-Type': 'application/json',
+        'X-Requested-With': 'XMLHttpRequest',
+      },
+      responseType: 'json',
+    });
+    const res = await axios.get('/_api/v3/check-username', { params: { username: event.target.value } });
+    setValidUserName(res.data.valid);
+  }, []);
+
+  const submitHandler: FormEventHandler = useCallback(async(e: any) => {
+    e.preventDefault();
+
+    if (isSubmittingDisabled) {
+      return;
+    }
+
+    setSubmittingDisabled(true);
+    setTimeout(() => {
+      setSubmittingDisabled(false);
+    }, 3000);
+
+    if (e.target.elements == null) {
+      return;
+    }
+
+    const formData = e.target.elements;
+
+    const {
+      'registerForm[username]': { value: username },
+      'registerForm[name]': { value: name },
+      'registerForm[email]': { value: email },
+      'registerForm[password]': { value: password },
+    } = formData;
+
+    const data = {
+      registerForm: {
+        username,
+        name,
+        email,
+        password,
+        'app:globalLang': formData['registerForm[app:globalLang]'].value,
+      },
+    };
+
+    try {
+      await apiv3Post('/installer', data);
+      window.location.href = '/';
+    }
+    catch (errs) {
+      const err = errs[0];
+      const code = err.code;
+
+      if (code === 'failed_to_login_after_install') {
+        toastError(t('installer.failed_to_login_after_install'));
+        setTimeout(() => { window.location.href = '/login' }, 700); // Wait 700 ms to show toastr
+      }
+
+      toastError(t('installer.failed_to_install'));
+    }
+  }, [isSubmittingDisabled, t]);
+
+  const hasErrorClass = isValidUserName ? '' : ' has-error';
+  const unavailableUserId = isValidUserName
+    ? ''
+    : <span><i className="icon-fw icon-ban" />{ t('installer.unavaliable_user_id') }</span>;
+
+  return (
+    <div data-testid="installerForm" className={`noLogin-dialog p-3 mx-auto${hasErrorClass}`}>
+      <div className="row">
+        <div className="col-md-12">
+          <p className="alert alert-success">
+            <strong>{ t('installer.create_initial_account') }</strong><br />
+            <small>{ t('installer.initial_account_will_be_administrator_automatically') }</small>
+          </p>
+        </div>
+      </div>
+      <div className="row">
+        <form role="form" id="register-form" className="col-md-12" onSubmit={submitHandler}>
+          <div className="dropdown mb-3">
+            <div className="d-flex dropdown-with-icon">
+              <i className="icon-bubbles border-0 rounded-0" />
+              <button
+                type="button"
+                className="btn btn-secondary dropdown-toggle text-right w-100 border-0 shadow-none"
+                id="dropdownLanguage"
+                data-testid="dropdownLanguage"
+                data-toggle="dropdown"
+                aria-haspopup="true"
+                aria-expanded="true"
+              >
+                <span className="float-left">
+                  {t('meta.display_name')}
+                </span>
+              </button>
+              <input
+                type="hidden"
+                name="registerForm[app:globalLang]"
+              />
+              <div className="dropdown-menu" aria-labelledby="dropdownLanguage">
+                {
+                  i18nConfig.locales.map((locale) => {
+                    let fixedT;
+                    if (i18n != null) {
+                      fixedT = i18n.getFixedT(locale);
+                      i18n.loadLanguages(i18nConfig.locales);
+                    }
+
+                    return (
+                      <button
+                        key={locale}
+                        data-testid={`dropdownLanguageMenu-${locale}`}
+                        className="dropdown-item"
+                        type="button"
+                        onClick={() => { i18next.changeLanguage(locale) }}
+                      >
+                        {fixedT?.('meta.display_name')}
+                      </button>
+                    );
+                  })
+                }
+              </div>
+            </div>
+          </div>
+
+          <div className={`input-group mb-3${hasErrorClass}`}>
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-user" /></span>
+            </div>
+            <input
+              data-testid="tiUsername"
+              type="text"
+              className="form-control"
+              placeholder={t('User ID')}
+              name="registerForm[username]"
+              // onBlur={checkUserName} // need not to check username before installation -- 2020.07.24 Yuki Takei
+              required
+            />
+          </div>
+          <p className="form-text">{ unavailableUserId }</p>
+
+          <div className="input-group mb-3">
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-tag" /></span>
+            </div>
+            <input
+              data-testid="tiName"
+              type="text"
+              className="form-control"
+              placeholder={t('Name')}
+              name="registerForm[name]"
+              required
+            />
+          </div>
+
+          <div className="input-group mb-3">
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-envelope" /></span>
+            </div>
+            <input
+              data-testid="tiEmail"
+              type="email"
+              className="form-control"
+              placeholder={t('Email')}
+              name="registerForm[email]"
+              required
+            />
+          </div>
+
+          <div className="input-group mb-3">
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-lock" /></span>
+            </div>
+            <input
+              data-testid="tiPassword"
+              type="password"
+              className="form-control"
+              placeholder={t('Password')}
+              name="registerForm[password]"
+              required
+            />
+          </div>
+
+          <div className="input-group mt-4 mb-3 d-flex justify-content-center">
+            <button
+              data-testid="btnSubmit"
+              type="submit"
+              className="btn-fill btn btn-register"
+              id="register"
+              disabled={isSubmittingDisabled}
+            >
+              <div className="eff"></div>
+              <span className="btn-label"><i className="icon-user-follow" /></span>
+              <span className="btn-label-text">{ t('Create') }</span>
+            </button>
+          </div>
+
+          <div className="input-group mt-4 d-flex justify-content-center">
+            <a href="https://growi.org" className="link-growi-org">
+              <span className="growi">GROWI</span>.<span className="org">ORG</span>
+            </a>
+          </div>
+        </form>
+      </div>
+    </div>
+  );
+});
+
+InstallerForm.displayName = 'InstallerForm';
+
+export default InstallerForm;

+ 3 - 3
packages/app/src/components/Layout/BasicLayout.tsx

@@ -7,7 +7,7 @@ import Sidebar from '../Sidebar';
 
 import { RawLayout } from './RawLayout';
 
-// const HotkeysManager = dynamic(() => import('../client/js/components/Hotkeys/HotkeysManager'), { ssr: false });
+const HotkeysManager = dynamic(() => import('../Hotkeys/HotkeysManager'), { ssr: false });
 // const PageCreateModal = dynamic(() => import('../client/js/components/PageCreateModal'), { ssr: false });
 const GrowiNavbarBottom = dynamic(() => import('../Navbar/GrowiNavbarBottom').then(mod => mod.GrowiNavbarBottom), { ssr: false });
 const ShortcutsModal = dynamic(() => import('../ShortcutsModal'), { ssr: false });
@@ -20,7 +20,7 @@ const PageRenameModal = dynamic(() => import('../PageRenameModal'), { ssr: false
 const PagePresentationModal = dynamic(() => import('../PagePresentationModal'), { ssr: false });
 const PageAccessoriesModal = dynamic(() => import('../PageAccessoriesModal'), { ssr: false });
 // Fab
-const Fab = dynamic(() => import('../Fab'), { ssr: false });
+const Fab = dynamic(() => import('../Fab').then(mod => mod.Fab), { ssr: false });
 
 
 type Props = {
@@ -58,7 +58,7 @@ export const BasicLayout = ({
       <PageRenameModal />
       <PagePresentationModal />
       <PageAccessoriesModal />
-      {/* <HotkeysManager /> */}
+      <HotkeysManager />
 
       <Fab />
 

+ 50 - 0
packages/app/src/components/Layout/ShareLinkLayout.tsx

@@ -0,0 +1,50 @@
+import React, { ReactNode } from 'react';
+
+import dynamic from 'next/dynamic';
+
+import { GrowiNavbar } from '../Navbar/GrowiNavbar';
+
+import { RawLayout } from './RawLayout';
+
+const PageCreateModal = dynamic(() => import('../PageCreateModal'), { ssr: false });
+const GrowiNavbarBottom = dynamic(() => import('../Navbar/GrowiNavbarBottom').then(mod => mod.GrowiNavbarBottom), { ssr: false });
+const ShortcutsModal = dynamic(() => import('../ShortcutsModal'), { ssr: false });
+const SystemVersion = dynamic(() => import('../SystemVersion'), { ssr: false });
+
+// Fab
+const Fab = dynamic(() => import('../Fab').then(mod => mod.Fab), { ssr: false });
+
+
+type Props = {
+  title: string
+  className?: string,
+  expandContainer?: boolean,
+  children?: ReactNode
+}
+
+export const ShareLinkLayout = ({
+  children, title, className, expandContainer,
+}: Props): JSX.Element => {
+
+  const myClassName = `${className ?? ''} ${expandContainer ? 'growi-layout-fluid' : ''}`;
+
+  return (
+    <RawLayout title={title} className={myClassName}>
+      <GrowiNavbar />
+
+      <div className="page-wrapper d-flex d-print-block">
+        <div className="flex-fill mw-0">
+          {children}
+        </div>
+      </div>
+
+      <GrowiNavbarBottom />
+
+      <Fab />
+
+      <ShortcutsModal />
+      <PageCreateModal />
+      <SystemVersion showShortcutsButton />
+    </RawLayout>
+  );
+};

+ 4 - 4
packages/app/src/components/LikeButtons.module.scss

@@ -1,11 +1,11 @@
 @use '~/styles/bootstrap/init' as bs;
 
-.btn-like {
-  :global {
+.btn-group-like :global {
+  .btn-like {
     box-shadow: none !important;
-  }
-  &:global {
+
     @include bs.button-outline-variant(rgba(bs.$secondary, 50%), lighten(bs.$red, 15%), rgba(lighten(bs.$red, 10%), 0.15), rgba(lighten(bs.$red, 10%), 0.5));
+
     &:not(:disabled):not(.disabled):active,
     &:not(:disabled):not(.disabled).active {
       color: lighten(bs.$red, 15%);

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

@@ -45,12 +45,12 @@ const LikeButtons: FC<LikeButtonsProps> = (props: LikeButtonsProps) => {
   }, [isGuestUser, isLiked]);
 
   return (
-    <div className="btn-group" role="group" aria-label="Like buttons">
+    <div className={`btn-group btn-group-like ${styles['btn-group-like']}`} role="group" aria-label="Like buttons">
       <button
         type="button"
         id="like-button"
         onClick={onLikeClicked}
-        className={`shadow-none btn btn-like ${styles['btn-like']} border-0
+        className={`shadow-none btn btn-like border-0
             ${isLiked ? 'active' : ''} ${isGuestUser ? 'disabled' : ''}`}
       >
         <i className={`fa ${isLiked ? 'fa-heart' : 'fa-heart-o'}`}></i>

+ 174 - 144
packages/app/src/components/LoginForm.jsx → packages/app/src/components/LoginForm.tsx

@@ -1,44 +1,64 @@
-import React from 'react';
+import React, {
+  useState, useEffect, useCallback,
+} from 'react';
 
 import { useTranslation } from 'next-i18next';
-import PropTypes from 'prop-types';
+import { useRouter } from 'next/router';
 import ReactCardFlip from 'react-card-flip';
 
+import { apiv3Post } from '~/client/util/apiv3-client';
 import { useCsrfToken } from '~/stores/context';
 
-class LoginForm extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      isRegistering: false,
-    };
-
-    this.switchForm = this.switchForm.bind(this);
-    this.handleLoginWithExternalAuth = this.handleLoginWithExternalAuth.bind(this);
-    this.renderLocalOrLdapLoginForm = this.renderLocalOrLdapLoginForm.bind(this);
-    this.renderExternalAuthLoginForm = this.renderExternalAuthLoginForm.bind(this);
-    this.renderExternalAuthInput = this.renderExternalAuthInput.bind(this);
-    this.renderRegisterForm = this.renderRegisterForm.bind(this);
+type LoginFormProps = {
+  username?: string,
+  name?: string,
+  email?: string,
+  isRegistrationEnabled: boolean,
+  isEmailAuthenticationEnabled: boolean,
+  registrationMode?: string,
+  registrationWhiteList: string[],
+  isPasswordResetEnabled: boolean,
+  isLocalStrategySetup: boolean,
+  isLdapStrategySetup: boolean,
+  objOfIsExternalAuthEnableds?: any,
+  isMailerSetup?: boolean
+}
+export const LoginForm = (props: LoginFormProps): JSX.Element => {
+  const { t } = useTranslation();
+  const router = useRouter();
+  const { data: csrfToken } = useCsrfToken();
 
+  const {
+    isLocalStrategySetup, isLdapStrategySetup, isPasswordResetEnabled, isRegistrationEnabled,
+    isEmailAuthenticationEnabled, registrationMode, registrationWhiteList, isMailerSetup,
+  } = props;
+  const isLocalOrLdapStrategiesEnabled = isLocalStrategySetup || isLdapStrategySetup;
+  // const isSomeExternalAuthEnabled = Object.values(objOfIsExternalAuthEnableds).some(elem => elem);
+  const isSomeExternalAuthEnabled = true;
+
+  // states
+  const [isRegistering, setIsRegistering] = useState(false);
+  const [username, setUsername] = useState('');
+  const [name, setName] = useState('');
+  const [email, setEmail] = useState('');
+  const [password, setPassword] = useState('');
+  const [registerErrors, setRegisterErrors] = useState<Error[]>([]);
+
+  useEffect(() => {
     const { hash } = window.location;
     if (hash === '#register') {
-      this.state.isRegistering = true;
+      setIsRegistering(true);
     }
-  }
-
-  switchForm() {
-    this.setState({ isRegistering: !this.state.isRegistering });
-  }
+  }, []);
 
-  handleLoginWithExternalAuth(e) {
+  // functions
+  const handleLoginWithExternalAuth = useCallback((e) => {
     const auth = e.currentTarget.id;
-    window.location.href = `/passport/${auth}`;
-  }
 
-  renderLocalOrLdapLoginForm() {
-    const { t, csrfToken, isLdapStrategySetup } = this.props;
+    window.location.href = `/passport/${auth}`;
+  }, []);
+  const renderLocalOrLdapLoginForm = useCallback(() => {
+    const { isLdapStrategySetup } = props;
 
     return (
       <form role="form" action="/login" method="post">
@@ -79,10 +99,8 @@ class LoginForm extends React.Component {
         </div>
       </form>
     );
-  }
-
-  renderExternalAuthInput(auth) {
-    const { t } = this.props;
+  }, [csrfToken, props, t]);
+  const renderExternalAuthInput = useCallback((auth) => {
     const authIconNames = {
       google: 'google',
       github: 'github',
@@ -95,7 +113,7 @@ class LoginForm extends React.Component {
 
     return (
       <div key={auth} className="col-6 my-2">
-        <button type="button" className="btn btn-fill rounded-0" id={auth} onClick={this.handleLoginWithExternalAuth}>
+        <button type="button" className="btn btn-fill rounded-0" id={auth} onClick={handleLoginWithExternalAuth}>
           <div className="eff"></div>
           <span className="btn-label">
             <i className={`fa fa-${authIconNames[auth]}`}></i>
@@ -105,10 +123,9 @@ class LoginForm extends React.Component {
         <div className="small text-right">by {auth} Account</div>
       </div>
     );
-  }
-
-  renderExternalAuthLoginForm() {
-    const { isLocalStrategySetup, isLdapStrategySetup, objOfIsExternalAuthEnableds } = this.props;
+  }, [handleLoginWithExternalAuth, t]);
+  const renderExternalAuthLoginForm = useCallback(() => {
+    const { isLocalStrategySetup, isLdapStrategySetup, objOfIsExternalAuthEnableds } = props;
     const isExternalAuthCollapsible = isLocalStrategySetup || isLdapStrategySetup;
     const collapsibleClass = isExternalAuthCollapsible ? 'collapse collapse-external-auth' : '';
 
@@ -121,7 +138,7 @@ class LoginForm extends React.Component {
                 if (!objOfIsExternalAuthEnableds[auth]) {
                   return;
                 }
-                return this.renderExternalAuthInput(auth);
+                return renderExternalAuthInput(auth);
               })}
             </div>
           </div>
@@ -140,22 +157,42 @@ class LoginForm extends React.Component {
         </div>
       </>
     );
-  }
+  }, [props, renderExternalAuthInput]);
 
-  renderRegisterForm() {
-    const {
-      t,
-      // appContainer,
-      csrfToken,
-      isEmailAuthenticationEnabled,
+  const handleRegisterFormSubmit = useCallback(async(e, requestPath) => {
+    e.preventDefault();
+
+    const registerForm = {
       username,
       name,
       email,
-      registrationMode,
-      registrationWhiteList,
-      isMailerSetup,
-    } = this.props;
+      password,
+    };
+    try {
+      const res = await apiv3Post(requestPath, { registerForm });
+      const { redirectTo } = res.data;
+      router.push(redirectTo);
+    }
+    catch (err) {
+      // Execute if error exists
+      if (err != null || err.length > 0) {
+        setRegisterErrors(err);
+      }
+    }
+    return;
+  }, [email, name, password, router, username]);
+
+  const resetRegisterErrors = useCallback(() => {
+    if (registerErrors.length === 0) return;
+    setRegisterErrors([]);
+  }, [registerErrors.length]);
+
+  const switchForm = useCallback(() => {
+    setIsRegistering(!isRegistering);
+    resetRegisterErrors();
+  }, [isRegistering, resetRegisterErrors]);
 
+  const renderRegisterForm = useCallback(() => {
     let registerAction = '/register';
 
     let submitText = t('Sign up');
@@ -179,7 +216,21 @@ class LoginForm extends React.Component {
           </p>
         )}
 
-        <form role="form" action={registerAction} method="post" id="register-form">
+        {
+          registerErrors != null && registerErrors.length > 0 && (
+            <p className="alert alert-danger">
+              {registerErrors.map((err, index) => {
+                return (
+                  <span key={index}>
+                    {t(`message.${err.message}`)}<br/>
+                  </span>
+                );
+              })}
+            </p>
+          )
+        }
+
+        <form role="form" onSubmit={e => handleRegisterFormSubmit(e, registerAction) } id="register-form">
 
           {!isEmailAuthenticationEnabled && (
             <div>
@@ -189,12 +240,14 @@ class LoginForm extends React.Component {
                     <i className="icon-user"></i>
                   </span>
                 </div>
+                {/* username */}
                 <input
                   type="text"
                   className="form-control rounded-0"
+                  onChange={(e) => { setUsername(e.target.value) }}
                   placeholder={t('User ID')}
-                  name="registerForm[username]"
-                  defaultValue={username}
+                  name="username"
+                  defaultValue={props.username}
                   required
                 />
               </div>
@@ -207,7 +260,14 @@ class LoginForm extends React.Component {
                     <i className="icon-tag"></i>
                   </span>
                 </div>
-                <input type="text" className="form-control rounded-0" placeholder={t('Name')} name="registerForm[name]" defaultValue={name} required />
+                {/* name */}
+                <input type="text"
+                  className="form-control rounded-0"
+                  onChange={(e) => { setName(e.target.value) }}
+                  placeholder={t('Name')}
+                  name="name"
+                  defaultValue={props.name}
+                  required />
               </div>
             </div>
           )}
@@ -218,7 +278,15 @@ class LoginForm extends React.Component {
                 <i className="icon-envelope"></i>
               </span>
             </div>
-            <input type="email" className="form-control rounded-0" placeholder={t('Email')} name="registerForm[email]" defaultValue={email} required />
+            {/* email */}
+            <input type="email"
+              className="form-control rounded-0"
+              onChange={(e) => { setEmail(e.target.value) }}
+              placeholder={t('Email')}
+              name="email"
+              defaultValue={props.email}
+              required
+            />
           </div>
 
           {registrationWhiteList.length > 0 && (
@@ -244,14 +312,24 @@ class LoginForm extends React.Component {
                     <i className="icon-lock"></i>
                   </span>
                 </div>
-                <input type="password" className="form-control rounded-0" placeholder={t('Password')} name="registerForm[password]" required />
+                {/* Password */}
+                <input type="password"
+                  className="form-control rounded-0"
+                  onChange={(e) => { setPassword(e.target.value) }}
+                  placeholder={t('Password')}
+                  name="password"
+                  required />
               </div>
             </div>
           )}
 
+          {/* Sign up button (submit) */}
           <div className="input-group justify-content-center my-4">
-            <input type="hidden" name="_csrf" value={csrfToken} />
-            <button type="submit" className="btn btn-fill rounded-0" id="register" disabled={(!isMailerSetup && isEmailAuthenticationEnabled)}>
+            <button
+              className="btn btn-fill rounded-0"
+              id="register"
+              disabled={(!isMailerSetup && isEmailAuthenticationEnabled)}
+            >
               <div className="eff"></div>
               <span className="btn-label">
                 <i className="icon-user-follow"></i>
@@ -265,7 +343,7 @@ class LoginForm extends React.Component {
 
         <div className="row">
           <div className="text-right col-12 mt-2 py-2">
-            <a href="#login" id="login" className="link-switch" onClick={this.switchForm}>
+            <a href="#login" id="login" className="link-switch" onClick={switchForm}>
               <i className="icon-fw icon-login"></i>
               {t('Sign in is here')}
             </a>
@@ -273,93 +351,45 @@ class LoginForm extends React.Component {
         </div>
       </React.Fragment>
     );
-  }
-
-  render() {
-    const {
-      t,
-      isLocalStrategySetup,
-      isLdapStrategySetup,
-      isRegistrationEnabled,
-      isPasswordResetEnabled,
-      objOfIsExternalAuthEnableds,
-    } = this.props;
-
-
-    const isLocalOrLdapStrategiesEnabled = isLocalStrategySetup || isLdapStrategySetup;
-    // const isSomeExternalAuthEnabled = Object.values(objOfIsExternalAuthEnableds).some(elem => elem);
-    const isSomeExternalAuthEnabled = true;
-
-    return (
-      <div className="noLogin-dialog mx-auto" id="noLogin-dialog">
-        <div className="row mx-0">
-          <div className="col-12">
-            <ReactCardFlip isFlipped={this.state.isRegistering} flipDirection="horizontal" cardZIndex="3">
-              <div className="front">
-                {isLocalOrLdapStrategiesEnabled && this.renderLocalOrLdapLoginForm()}
-                {isSomeExternalAuthEnabled && this.renderExternalAuthLoginForm()}
-                {isLocalOrLdapStrategiesEnabled && isPasswordResetEnabled && (
-                  <div className="text-right mb-2">
-                    <a href="/forgot-password" className="d-block link-switch">
-                      <i className="icon-key"></i> {t('forgot_password.forgot_password')}
-                    </a>
-                  </div>
-                )}
-                {isRegistrationEnabled && (
-                  <div className="text-right mb-2">
-                    <a href="#register" id="register" className="link-switch" onClick={this.switchForm}>
-                      <i className="ti ti-check-box"></i> {t('Sign up is here')}
-                    </a>
-                  </div>
-                )}
-              </div>
-              <div className="back">
-                {isRegistrationEnabled && this.renderRegisterForm()}
-              </div>
-            </ReactCardFlip>
-          </div>
+  }, [handleRegisterFormSubmit, isEmailAuthenticationEnabled, isMailerSetup,
+      props.email, props.name, props.username,
+      registerErrors, registrationMode, registrationWhiteList, switchForm, t]);
+
+  return (
+    <div className="noLogin-dialog mx-auto" id="noLogin-dialog">
+      <div className="row mx-0">
+        <div className="col-12">
+          <ReactCardFlip isFlipped={isRegistering} flipDirection="horizontal" cardZIndex="3">
+            <div className="front">
+              {isLocalOrLdapStrategiesEnabled && renderLocalOrLdapLoginForm()}
+              {isSomeExternalAuthEnabled && renderExternalAuthLoginForm()}
+              {isLocalOrLdapStrategiesEnabled && isPasswordResetEnabled && (
+                <div className="text-right mb-2">
+                  <a href="/forgot-password" className="d-block link-switch">
+                    <i className="icon-key"></i> {t('forgot_password.forgot_password')}
+                  </a>
+                </div>
+              )}
+              {/* Sign up link */}
+              {isRegistrationEnabled && (
+                <div className="text-right mb-2">
+                  <a href="#register" id="register" className="link-switch" onClick={switchForm}>
+                    <i className="ti ti-check-box"></i> {t('Sign up is here')}
+                  </a>
+                </div>
+              )}
+            </div>
+            <div className="back">
+              {/* Register form for /login#register */}
+              {isRegistrationEnabled && renderRegisterForm()}
+            </div>
+          </ReactCardFlip>
         </div>
-        <a href="https://growi.org" className="link-growi-org pl-3">
-          <span className="growi">GROWI</span>.<span className="org">ORG</span>
-        </a>
       </div>
-    );
-  }
-
-}
+      <a href="https://growi.org" className="link-growi-org pl-3">
+        <span className="growi">GROWI</span>.<span className="org">ORG</span>
+      </a>
+    </div>
+  );
 
-LoginForm.propTypes = {
-  // i18next
-  t: PropTypes.func.isRequired,
-  // appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-
-  csrfToken: PropTypes.string,
-  isRegistering: PropTypes.bool,
-  username: PropTypes.string,
-  name: PropTypes.string,
-  email: PropTypes.string,
-  isRegistrationEnabled: PropTypes.bool,
-  registrationMode: PropTypes.string,
-  registrationWhiteList: PropTypes.array,
-  isPasswordResetEnabled: PropTypes.bool,
-  isEmailAuthenticationEnabled: PropTypes.bool,
-  isLocalStrategySetup: PropTypes.bool,
-  isLdapStrategySetup: PropTypes.bool,
-  objOfIsExternalAuthEnableds: PropTypes.object,
-  isMailerSetup: PropTypes.bool,
 };
-
-const LoginFormWrapperFC = (props) => {
-  const { t } = useTranslation();
-  const { data: csrfToken } = useCsrfToken();
-
-  return <LoginForm t={t} csrfToken={csrfToken} {...props} />;
-};
-
-/**
- * Wrapper component for using unstated
- */
-// const LoginFormWrapper = withUnstatedContainers(LoginFormWrapperFC, [AppContainer]);
-
-// export default LoginForm;
-export default LoginFormWrapperFC;

+ 0 - 1
packages/app/src/components/Me/BasicInfoSettings.tsx

@@ -109,7 +109,6 @@ export const BasicInfoSettings = (): JSX.Element => {
             i18nConfig.locales.map((locale) => {
               if (i18n == null) { return }
               const fixedT = i18n.getFixedT(locale);
-              i18n.loadLanguages(i18nConfig.locales);
 
               return (
                 <div key={locale} className="custom-control custom-radio custom-control-inline">

+ 18 - 25
packages/app/src/components/Navbar/GrowiContextualSubNavigation.tsx

@@ -179,8 +179,8 @@ const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps):
   const { data: currentUser } = useCurrentUser();
   const { data: isGuestUser } = useIsGuestUser();
   const { data: isSharedUser } = useIsSharedUser();
-  const { data: shareLinkId } = useShareLinkId();
   const { data: isNotFound } = useIsNotFound();
+  const { data: shareLinkId } = useShareLinkId();
 
   const { data: isAbleToShowPageManagement } = useIsAbleToShowPageManagement();
   const { data: isAbleToShowTagLabel } = useIsAbleToShowTagLabel();
@@ -296,14 +296,6 @@ const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps):
 
 
   const ControlComponents = useCallback(() => {
-    if (currentPage == null || pageId == null) {
-      return <></>;
-    }
-
-    function onPageEditorModeButtonClicked(viewType) {
-      mutateEditorMode(viewType);
-    }
-
     const additionalMenuItemsRenderer = () => {
       if (revisionId == null || pageId == null) {
         return <></>;
@@ -323,24 +315,26 @@ const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps):
 
           { isViewMode && (
             <div className="h-50 w-100">
-              <SubNavButtons
-                isCompactMode={isCompactMode}
-                pageId={pageId}
-                revisionId={revisionId}
-                shareLinkId={shareLinkId}
-                path={path}
-                disableSeenUserInfoPopover={isSharedUser}
-                showPageControlDropdown={isAbleToShowPageManagement}
-                additionalMenuItemRenderer={additionalMenuItemsRenderer}
-                onClickDuplicateMenuItem={duplicateItemClickedHandler}
-                onClickRenameMenuItem={renameItemClickedHandler}
-                onClickDeleteMenuItem={deleteItemClickedHandler}
-              />
+              { pageId != null && (
+                <SubNavButtons
+                  isCompactMode={isCompactMode}
+                  pageId={pageId}
+                  revisionId={revisionId}
+                  shareLinkId={shareLinkId}
+                  path={path}
+                  disableSeenUserInfoPopover={isSharedUser}
+                  showPageControlDropdown={isAbleToShowPageManagement}
+                  additionalMenuItemRenderer={additionalMenuItemsRenderer}
+                  onClickDuplicateMenuItem={duplicateItemClickedHandler}
+                  onClickRenameMenuItem={renameItemClickedHandler}
+                  onClickDeleteMenuItem={deleteItemClickedHandler}
+                />
+              ) }
             </div>
           ) }
           {isAbleToShowPageEditorModeManager && (
             <PageEditorModeManager
-              onPageEditorModeButtonClicked={onPageEditorModeButtonClicked}
+              onPageEditorModeButtonClicked={viewType => mutateEditorMode(viewType)}
               isBtnDisabled={isGuestUser}
               editorMode={editorMode}
             />
@@ -356,7 +350,7 @@ const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps):
       </>
     );
   // eslint-disable-next-line max-len
-  }, [currentPage, currentUser, pageId, revisionId, shareLinkId, path, editorMode, isCompactMode, isViewMode, isSharedUser, isAbleToShowPageManagement, isAbleToShowPageEditorModeManager, isLinkSharingDisabled, isGuestUser, isPageTemplateModalShown, duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler, mutateEditorMode, templateMenuItemClickHandler]);
+  }, [currentUser, pageId, revisionId, shareLinkId, path, editorMode, isCompactMode, isViewMode, isSharedUser, isAbleToShowPageManagement, isAbleToShowPageEditorModeManager, isLinkSharingDisabled, isGuestUser, isPageTemplateModalShown, duplicateItemClickedHandler, renameItemClickedHandler, deleteItemClickedHandler, mutateEditorMode, templateMenuItemClickHandler]);
 
   if (currentPathname == null) {
     return <></>;
@@ -375,7 +369,6 @@ const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps):
       isGuestUser={isGuestUser}
       isDrawerMode={isDrawerMode}
       isCompactMode={isCompactMode}
-      isNotFound={isNotFound}
       tags={isViewMode ? tagsInfoData?.tags : tagsForEditors}
       tagsUpdatedHandler={isViewMode ? tagsUpdatedHandlerForViewMode : tagsUpdatedHandlerForEditMode}
       controls={ControlComponents}

+ 4 - 5
packages/app/src/components/Navbar/GrowiNavbar.tsx

@@ -144,18 +144,17 @@ export const GrowiNavbar = (): JSX.Element => {
         {appTitle}
       </div>
 
-
       {/* Navbar Right  */}
       <ul className="navbar-nav ml-auto">
         <NavbarRight />
         <Confidential confidential={confidential} />
       </ul>
 
-      { isSearchServiceConfigured && !isDeviceSmallerThanMd && !isSearchPage && (
-        <div className="grw-global-search-container position-absolute">
+      <div className="grw-global-search-container position-absolute">
+        { isSearchServiceConfigured && !isDeviceSmallerThanMd && !isSearchPage && (
           <GlobalSearch />
-        </div>
-      ) }
+        ) }
+      </div>
     </nav>
   );
 

+ 16 - 19
packages/app/src/components/Navbar/GrowiSubNavigation.tsx

@@ -35,7 +35,6 @@ export type GrowiSubNavigationProps = {
   isGuestUser?: boolean,
   isDrawerMode?: boolean,
   isCompactMode?: boolean,
-  isNotFound?: boolean,
   tags?: string[],
   tagsUpdatedHandler?: (newTags: string[]) => Promise<void> | void,
   controls: React.FunctionComponent,
@@ -49,7 +48,7 @@ export const GrowiSubNavigation = (props: GrowiSubNavigationProps): JSX.Element
   const {
     page,
     showDrawerToggler, showTagLabel, showPageAuthors,
-    isGuestUser, isDrawerMode, isCompactMode, isNotFound,
+    isGuestUser, isDrawerMode, isCompactMode,
     tags, tagsUpdatedHandler,
     controls: Controls,
     additionalClasses = [],
@@ -87,23 +86,21 @@ export const GrowiSubNavigation = (props: GrowiSubNavigationProps): JSX.Element
           <PagePathNav pageId={pageId} pagePath={path} isSingleLineMode={isEditorMode} isCompactMode={isCompactMode} />
         </div>
       </div>
-      {/* Right side. isNotFound for avoid flicker when called ForbiddenPage.tsx */}
-      { !isNotFound && (
-        <div className="d-flex">
-          <Controls />
-          {/* Page Authors */}
-          { (showPageAuthors && !isCompactMode) && (
-            <ul className={`${AuthorInfoStyles['grw-author-info']} text-nowrap border-left d-none d-lg-block d-edit-none py-2 pl-4 mb-0 ml-3`}>
-              <li className="pb-1">
-                <AuthorInfo user={creator as IUser} date={createdAt} locate="subnav" />
-              </li>
-              <li className="mt-1 pt-1 border-top">
-                <AuthorInfo user={lastUpdateUser as IUser} date={updatedAt} mode="update" locate="subnav" />
-              </li>
-            </ul>
-          ) }
-        </div>
-      ) }
+      {/* Right side. */}
+      <div className="d-flex">
+        <Controls />
+        {/* Page Authors */}
+        { (showPageAuthors && !isCompactMode) && (
+          <ul className={`${AuthorInfoStyles['grw-author-info']} text-nowrap border-left d-none d-lg-block d-edit-none py-2 pl-4 mb-0 ml-3`}>
+            <li className="pb-1">
+              <AuthorInfo user={creator as IUser} date={createdAt} locate="subnav" />
+            </li>
+            <li className="mt-1 pt-1 border-top">
+              <AuthorInfo user={lastUpdateUser as IUser} date={updatedAt} mode="update" locate="subnav" />
+            </li>
+          </ul>
+        ) }
+      </div>
     </div>
   );
 };

+ 3 - 13
packages/app/src/components/Page.tsx

@@ -8,10 +8,9 @@ import dynamic from 'next/dynamic';
 
 import { HtmlElementNode } from 'rehype-toc';
 
-import { blinkSectionHeaderAtBoot } from '~/client/util/blink-section-header';
 // import { getOptionsToSave } from '~/client/util/editor';
 import {
-  useIsGuestUser, useIsBlinkedHeaderAtBoot, useCurrentPageTocNode,
+  useIsGuestUser, useCurrentPageTocNode, useShareLinkId,
 } from '~/stores/context';
 import {
   useSWRxSlackChannels, useIsSlackEnabled, usePageTagsForEditors, useIsEnabledUnsavedWarning,
@@ -201,7 +200,8 @@ export const Page = (props) => {
     tocRef.current = toc;
   }, []);
 
-  const { data: currentPage } = useSWRxCurrentPage();
+  const { data: shareLinkId } = useShareLinkId();
+  const { data: currentPage } = useSWRxCurrentPage(shareLinkId ?? undefined);
   const { data: editorMode } = useEditorMode();
   const { data: isGuestUser } = useIsGuestUser();
   const { data: isMobile } = useIsMobile();
@@ -210,20 +210,10 @@ export const Page = (props) => {
   const { data: pageTags } = usePageTagsForEditors(null); // TODO: pass pageId
   const { data: rendererOptions } = useViewOptions(storeTocNodeHandler);
   const { mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
-  const { data: isBlinkedAtBoot, mutate: mutateBlinkedAtBoot } = useIsBlinkedHeaderAtBoot();
   const { mutate: mutateCurrentPageTocNode } = useCurrentPageTocNode();
 
   const pageRef = useRef(null);
 
-  useEffect(() => {
-    if (isBlinkedAtBoot) {
-      return;
-    }
-
-    blinkSectionHeaderAtBoot();
-    mutateBlinkedAtBoot(true);
-  }, [isBlinkedAtBoot, mutateBlinkedAtBoot]);
-
   useEffect(() => {
     mutateCurrentPageTocNode(tocRef.current);
   // eslint-disable-next-line react-hooks/exhaustive-deps

+ 9 - 13
packages/app/src/components/Page/DisplaySwitcher.tsx

@@ -6,7 +6,7 @@ import dynamic from 'next/dynamic';
 
 // import { smoothScrollIntoView } from '~/client/util/smooth-scroll';
 import {
-  useCurrentPagePath, useIsSharedUser, useIsEditable, useIsUserPage, usePageUser, useShareLinkId, useIsNotFound,
+  useCurrentPagePath, useIsSharedUser, useIsEditable, useShareLinkId, useIsNotFound,
 } from '~/stores/context';
 import { useDescendantsPageListModal } from '~/stores/modal';
 import { useSWRxCurrentPage } from '~/stores/page';
@@ -16,23 +16,20 @@ import CountBadge from '../Common/CountBadge';
 import CustomTabContent from '../CustomNavigation/CustomTabContent';
 import PageListIcon from '../Icons/PageListIcon';
 import { Page } from '../Page';
-// import PageEditorByHackmd from '../PageEditorByHackmd';
 import TableOfContents from '../TableOfContents';
-import { UserInfoProps } from '../User/UserInfo';
-
 
 import styles from './DisplaySwitcher.module.scss';
 
-
-const { isTopPage } = pagePathUtils;
+const { isTopPage, isUsersHomePage } = pagePathUtils;
 
 
 const PageEditor = dynamic(() => import('../PageEditor'), { ssr: false });
+const PageEditorByHackmd = dynamic(() => import('../PageEditorByHackmd').then(mod => mod.PageEditorByHackmd), { ssr: false });
 const EditorNavbarBottom = dynamic(() => import('../PageEditor/EditorNavbarBottom'), { ssr: false });
 const HashChanged = dynamic(() => import('../EventListeneres/HashChanged'), { ssr: false });
-const ContentLinkButtons = dynamic(() => import('../ContentLinkButtons'), { ssr: false });
+const ContentLinkButtons = dynamic(() => import('../ContentLinkButtons').then(mod => mod.ContentLinkButtons), { ssr: false });
 const NotFoundPage = dynamic(() => import('../NotFoundPage'), { ssr: false });
-const UserInfo = dynamic<UserInfoProps>(() => import('../User/UserInfo').then(mod => mod.UserInfo), { ssr: false });
+const UserInfo = dynamic(() => import('../User/UserInfo').then(mod => mod.UserInfo), { ssr: false });
 
 
 const PageView = React.memo((): JSX.Element => {
@@ -41,19 +38,18 @@ const PageView = React.memo((): JSX.Element => {
   const { data: currentPagePath } = useCurrentPagePath();
   const { data: isSharedUser } = useIsSharedUser();
   const { data: shareLinkId } = useShareLinkId();
-  const { data: isUserPage } = useIsUserPage();
-  const { data: pageUser } = usePageUser();
   const { data: isNotFound } = useIsNotFound();
   const { data: currentPage } = useSWRxCurrentPage(shareLinkId ?? undefined);
   const { open: openDescendantPageListModal } = useDescendantsPageListModal();
 
   const isTopPagePath = isTopPage(currentPagePath ?? '');
+  const isUsersHomePagePath = isUsersHomePage(currentPagePath ?? '');
 
   return (
     <div className="d-flex flex-column flex-lg-row">
 
       <div className="flex-grow-1 flex-basis-0 mw-0">
-        { isUserPage && pageUser != null && <UserInfo pageUser={pageUser} />}
+        { isUsersHomePagePath && <UserInfo /> }
         { !isNotFound && <Page /> }
         { isNotFound && <NotFoundPage /> }
       </div>
@@ -98,7 +94,7 @@ const PageView = React.memo((): JSX.Element => {
 
             <div className="d-none d-lg-block">
               <TableOfContents />
-              <ContentLinkButtons />
+              { isUsersHomePagePath && <ContentLinkButtons /> }
             </div>
 
           </div>
@@ -145,7 +141,7 @@ const DisplaySwitcher = React.memo((): JSX.Element => {
           isEditable
             ? (
               <div id="page-editor-with-hackmd">
-                {/* <PageEditorByHackmd /> */}
+                <PageEditorByHackmd />
               </div>
             )
             : <></>

+ 0 - 5
packages/app/src/components/Page/RevisionRenderer.tsx

@@ -2,12 +2,7 @@ import React from 'react';
 
 import ReactMarkdown from 'react-markdown';
 
-import { blinkElem } from '~/client/util/blink-section-header';
-import { addSmoothScrollEvent } from '~/client/util/smooth-scroll';
-import { CustomWindow } from '~/interfaces/global';
 import { RendererOptions } from '~/services/renderer/renderer';
-import { useCurrentPathname, useInterceptorManager } from '~/stores/context';
-import { useEditorSettings } from '~/stores/editor';
 import loggerFactory from '~/utils/logger';
 
 

+ 0 - 52
packages/app/src/components/Page/ShareLinkAlert.jsx

@@ -1,52 +0,0 @@
-import React from 'react';
-
-import { useTranslation } from 'next-i18next';
-
-const ShareLinkAlert = () => {
-  const { t } = useTranslation();
-
-  const shareContent = document.getElementById('is-shared-page');
-  const expiredAt = shareContent.getAttribute('data-share-link-expired-at');
-  const createdAt = shareContent.getAttribute('data-share-link-created-at');
-
-  function generateRatio() {
-    const wholeTime = new Date(expiredAt).getTime() - new Date(createdAt).getTime();
-    const remainingTime = new Date(expiredAt).getTime() - new Date().getTime();
-    return remainingTime / wholeTime;
-  }
-
-  let ratio = 1;
-
-  if (expiredAt !== '') {
-    ratio = generateRatio();
-  }
-
-  function specifyColor() {
-    let color;
-    if (ratio >= 0.75) {
-      color = 'success';
-    }
-    else if (ratio < 0.75 && ratio >= 0.5) {
-      color = 'info';
-    }
-    else if (ratio < 0.5 && ratio >= 0.25) {
-      color = 'warning';
-    }
-    else {
-      color = 'danger';
-    }
-    return color;
-  }
-
-  return (
-    <p className={`alert alert-${specifyColor()} py-3 px-4 d-edit-none`}>
-      <i className="icon-fw icon-link"></i>
-      {(expiredAt === '' ? <span>{t('page_page.notice.no_deadline')}</span>
-      // eslint-disable-next-line react/no-danger
-        : <span dangerouslySetInnerHTML={{ __html: t('page_page.notice.expiration', { expiredAt }) }} />
-      )}
-    </p>
-  );
-};
-
-export default ShareLinkAlert;

+ 52 - 0
packages/app/src/components/Page/ShareLinkAlert.tsx

@@ -0,0 +1,52 @@
+import React, { FC } from 'react';
+
+import { useTranslation } from 'next-i18next';
+
+const generateRatio = (expiredAt: Date, createdAt: Date): number => {
+  const wholeTime = new Date(expiredAt).getTime() - new Date(createdAt).getTime();
+  const remainingTime = new Date(expiredAt).getTime() - new Date().getTime();
+  return remainingTime / wholeTime;
+};
+
+const getAlertColor = (ratio: number): string => {
+  let color: string;
+
+  if (ratio >= 0.75) {
+    color = 'success';
+  }
+  else if (ratio < 0.75 && ratio >= 0.5) {
+    color = 'info';
+  }
+  else if (ratio < 0.5 && ratio >= 0.25) {
+    color = 'warning';
+  }
+  else {
+    color = 'danger';
+  }
+  return color;
+};
+
+type Props = {
+  createdAt: Date,
+  expiredAt?: Date,
+}
+
+const ShareLinkAlert: FC<Props> = (props: Props) => {
+  const { t } = useTranslation();
+  const { expiredAt, createdAt } = props;
+
+  const ratio = expiredAt != null ? generateRatio(expiredAt, createdAt) : 1;
+  const alertColor = getAlertColor(ratio);
+
+  return (
+    <p className={`alert alert-${alertColor} my-3 px-4 d-edit-none`}>
+      <i className="icon-fw icon-link"></i>
+      {(expiredAt === null ? <span>{t('page_page.notice.no_deadline')}</span>
+      // eslint-disable-next-line react/no-danger
+        : <span dangerouslySetInnerHTML={{ __html: t('page_page.notice.expiration', { expiredAt }) }} />
+      )}
+    </p>
+  );
+};
+
+export default ShareLinkAlert;

+ 62 - 65
packages/app/src/components/PageAttachment.tsx

@@ -1,65 +1,49 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import React, {
+  useCallback, useMemo, useState,
+} from 'react';
 
-import { useTranslation } from 'next-i18next';
+import { HasObjectId, IAttachment } from '@growi/core';
 
 import { useSWRxAttachments } from '~/stores/attachment';
 import { useEditingMarkdown, useCurrentPageId, useIsGuestUser } from '~/stores/context';
 
-import DeleteAttachmentModal from './PageAttachment/DeleteAttachmentModal';
-import PageAttachmentList from './PageAttachment/PageAttachmentList';
+import { DeleteAttachmentModal } from './PageAttachment/DeleteAttachmentModal';
+import { PageAttachmentList } from './PageAttachment/PageAttachmentList';
 import PaginationWrapper from './PaginationWrapper';
 
 // Utility
-const checkIfFileInUse = (markdown: string, attachment) => {
-  return markdown.match(attachment._id);
-};
-
-// Custom hook that handles processes related to inUseAttachments
-const useInUseAttachments = (attachments) => {
-  const { data: markdown } = useEditingMarkdown();
-  const [inUse, setInUse] = useState<any>({});
-
-  // Update inUse when either of attachments or markdown is updated
-  useEffect(() => {
-    if (markdown == null) {
-      return;
-    }
-
-    const newInUse = {};
-
-    for (const attachment of attachments) {
-      newInUse[attachment._id] = checkIfFileInUse(markdown, attachment);
-    }
-
-    setInUse(newInUse);
-  }, [attachments, markdown]);
-
-  return inUse;
+const checkIfFileInUse = (markdown: string, attachment): boolean => {
+  return markdown.indexOf(attachment._id) >= 0;
 };
 
 const PageAttachment = (): JSX.Element => {
-  const { t } = useTranslation();
-
   // Static SWRs
   const { data: pageId } = useCurrentPageId();
   const { data: isGuestUser } = useIsGuestUser();
+  const { data: markdown } = useEditingMarkdown();
 
   // States
   const [pageNumber, setPageNumber] = useState(1);
-  const [attachmentToDelete, setAttachmentToDelete] = useState<any>(undefined);
+  const [attachmentToDelete, setAttachmentToDelete] = useState<(IAttachment & HasObjectId) | null>(null);
   const [deleting, setDeleting] = useState(false);
   const [deleteError, setDeleteError] = useState('');
 
   // SWRs
   const { data: dataAttachments, remove } = useSWRxAttachments(pageId, pageNumber);
-  const {
-    attachments = [],
-    totalAttachments = 0,
-    limit,
-  } = dataAttachments ?? {};
 
   // Custom hooks
-  const inUseAttachments = useInUseAttachments(attachments);
+  const inUseAttachmentsMap: { [id: string]: boolean } | undefined = useMemo(() => {
+    if (markdown == null || dataAttachments == null) {
+      return undefined;
+    }
+
+    const attachmentEntries = dataAttachments.attachments
+      .map((attachment) => {
+        return [attachment._id, checkIfFileInUse(markdown, attachment)];
+      });
+
+    return Object.fromEntries(attachmentEntries);
+  }, [dataAttachments, markdown]);
 
   // Methods
   const onChangePageHandler = useCallback((newPageNumber: number) => {
@@ -70,7 +54,7 @@ const PageAttachment = (): JSX.Element => {
     setAttachmentToDelete(attachment);
   }, []);
 
-  const onAttachmentDeleteClickedConfirmHandler = useCallback(async(attachment) => {
+  const onAttachmentDeleteClickedConfirmHandler = useCallback(async(attachment: IAttachment & HasObjectId) => {
     setDeleting(true);
 
     try {
@@ -91,22 +75,32 @@ const PageAttachment = (): JSX.Element => {
   }, []);
 
   // Renderers
-  const renderDeleteAttachmentModal = useCallback(() => {
-    if (isGuestUser) {
-      return <></>;
-    }
-
-    if (attachments.length === 0) {
+  const renderPageAttachmentList = useCallback(() => {
+    if (dataAttachments == null || inUseAttachmentsMap == null) {
       return (
-        <div data-testid="page-attachment">
-          {t('No_attachments_yet')}
+        <div className="text-muted text-center">
+          <i className="fa fa-2x fa-spinner fa-pulse mr-1"></i>
         </div>
       );
     }
 
-    let deleteInUse = null;
-    if (attachmentToDelete != null) {
-      deleteInUse = inUseAttachments[attachmentToDelete._id] || false;
+    return (
+      <PageAttachmentList
+        attachments={dataAttachments.attachments}
+        inUse={inUseAttachmentsMap}
+        onAttachmentDeleteClicked={onAttachmentDeleteClicked}
+        isUserLoggedIn={!isGuestUser}
+      />
+    );
+  }, [dataAttachments, inUseAttachmentsMap, isGuestUser, onAttachmentDeleteClicked]);
+
+  const renderDeleteAttachmentModal = useCallback(() => {
+    if (isGuestUser) {
+      return <></>;
+    }
+
+    if (dataAttachments == null || dataAttachments.attachments.length === 0 || attachmentToDelete == null) {
+      return <></>;
     }
 
     const isOpen = attachmentToDelete != null;
@@ -114,36 +108,39 @@ const PageAttachment = (): JSX.Element => {
     return (
       <DeleteAttachmentModal
         isOpen={isOpen}
-        animation="false"
         toggle={onToggleHandler}
         attachmentToDelete={attachmentToDelete}
-        inUse={deleteInUse}
         deleting={deleting}
         deleteError={deleteError}
         onAttachmentDeleteClickedConfirm={onAttachmentDeleteClickedConfirmHandler}
       />
     );
   // eslint-disable-next-line max-len
-  }, [attachmentToDelete, attachments.length, deleteError, deleting, inUseAttachments, isGuestUser, onAttachmentDeleteClickedConfirmHandler, onToggleHandler, t]);
+  }, [attachmentToDelete, dataAttachments, deleteError, deleting, isGuestUser, onAttachmentDeleteClickedConfirmHandler, onToggleHandler]);
 
-  return (
-    <div data-testid="page-attachment">
-      <PageAttachmentList
-        attachments={attachments}
-        inUse={inUseAttachments}
-        onAttachmentDeleteClicked={onAttachmentDeleteClicked}
-        isUserLoggedIn={!isGuestUser}
-      />
-
-      {renderDeleteAttachmentModal()}
+  const renderPaginationWrapper = useCallback(() => {
+    if (dataAttachments == null || dataAttachments.attachments.length === 0) {
+      return <></>;
+    }
 
+    return (
       <PaginationWrapper
         activePage={pageNumber}
         changePage={onChangePageHandler}
-        totalItemsCount={totalAttachments}
-        pagingLimit={limit}
+        totalItemsCount={dataAttachments.totalAttachments}
+        pagingLimit={dataAttachments.limit}
         align="center"
       />
+    );
+  }, [dataAttachments, onChangePageHandler, pageNumber]);
+
+  return (
+    <div data-testid="page-attachment">
+      {renderPageAttachmentList()}
+
+      {renderDeleteAttachmentModal()}
+
+      {renderPaginationWrapper()}
     </div>
   );
 };

+ 0 - 97
packages/app/src/components/PageAttachment/DeleteAttachmentModal.jsx

@@ -1,97 +0,0 @@
-/* eslint-disable react/prop-types */
-import React from 'react';
-
-import {
-  Button,
-  Modal, ModalHeader, ModalBody, ModalFooter,
-} from 'reactstrap';
-
-import { UserPicture } from '@growi/ui';
-import Username from '../User/Username';
-
-export default class DeleteAttachmentModal extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this._onDeleteConfirm = this._onDeleteConfirm.bind(this);
-  }
-
-  _onDeleteConfirm() {
-    this.props.onAttachmentDeleteClickedConfirm(this.props.attachmentToDelete);
-  }
-
-  iconNameByFormat(format) {
-    if (format.match(/image\/.+/i)) {
-      return 'icon-picture';
-    }
-
-    return 'icon-doc';
-  }
-
-  renderByFileFormat(attachment) {
-    const content = (attachment.fileFormat.match(/image\/.+/i))
-      ? <img src={attachment.filePathProxied} alt="deleting image" />
-      : '';
-
-
-    return (
-      <div className="attachment-delete-image">
-        <p>
-          <i className={this.iconNameByFormat(attachment.fileFormat)}></i> {attachment.originalName}
-        </p>
-        <p>
-          uploaded by <UserPicture user={attachment.creator} size="sm"></UserPicture> <Username user={attachment.creator}></Username>
-        </p>
-        {content}
-      </div>
-    );
-  }
-
-  render() {
-    const attachment = this.props.attachmentToDelete;
-    if (attachment === null) {
-      return null;
-    }
-
-    const props = Object.assign({}, this.props);
-    delete props.onAttachmentDeleteClickedConfirm;
-    delete props.attachmentToDelete;
-    delete props.inUse;
-    delete props.deleting;
-    delete props.deleteError;
-
-    let deletingIndicator = '';
-    if (this.props.deleting) {
-      deletingIndicator = <div className="speeding-wheel-sm"></div>;
-    }
-    if (this.props.deleteError) {
-      deletingIndicator = <span>{this.props.deleteError}</span>;
-    }
-
-    const renderAttachment = this.renderByFileFormat(attachment);
-
-    return (
-      <Modal {...props} className="attachment-delete-modal" bssize="large" aria-labelledby="contained-modal-title-lg">
-        <ModalHeader tag="h4" toggle={this.props.toggle} className="bg-danger text-light">
-          <span id="contained-modal-title-lg">Delete attachment?</span>
-        </ModalHeader>
-        <ModalBody>
-          {renderAttachment}
-        </ModalBody>
-        <ModalFooter>
-          <div className="mr-3 d-inline-block">
-            {deletingIndicator}
-          </div>
-          <Button
-            color="danger"
-            onClick={this._onDeleteConfirm}
-            disabled={this.props.deleting}
-          >Delete!
-          </Button>
-        </ModalFooter>
-      </Modal>
-    );
-  }
-
-}

+ 98 - 0
packages/app/src/components/PageAttachment/DeleteAttachmentModal.tsx

@@ -0,0 +1,98 @@
+/* eslint-disable react/prop-types */
+import React, { useCallback } from 'react';
+
+import { HasObjectId, IAttachment } from '@growi/core';
+import { UserPicture } from '@growi/ui';
+import {
+  Button,
+  Modal, ModalHeader, ModalBody, ModalFooter,
+} from 'reactstrap';
+
+import Username from '../User/Username';
+
+
+function iconNameByFormat(format: string): string {
+  if (format.match(/image\/.+/i)) {
+    return 'icon-picture';
+  }
+
+  return 'icon-doc';
+}
+
+
+type Props = {
+  isOpen: boolean,
+  toggle: () => void,
+  attachmentToDelete: IAttachment & HasObjectId | null,
+  deleting: boolean,
+  deleteError: string,
+  onAttachmentDeleteClickedConfirm?: (attachment: IAttachment & HasObjectId) => Promise<void>,
+}
+
+export const DeleteAttachmentModal = (props: Props): JSX.Element => {
+
+  const {
+    isOpen, toggle,
+    attachmentToDelete, deleting, deleteError,
+    onAttachmentDeleteClickedConfirm,
+  } = props;
+
+  const onDeleteConfirm = useCallback(() => {
+    if (attachmentToDelete == null || onAttachmentDeleteClickedConfirm == null) {
+      return;
+    }
+    onAttachmentDeleteClickedConfirm(attachmentToDelete);
+  }, [attachmentToDelete, onAttachmentDeleteClickedConfirm]);
+
+  const renderByFileFormat = useCallback((attachment) => {
+    const content = (attachment.fileFormat.match(/image\/.+/i))
+      // eslint-disable-next-line @next/next/no-img-element
+      ? <img src={attachment.filePathProxied} alt="deleting image" />
+      : '';
+
+
+    return (
+      <div className="attachment-delete-image">
+        <p>
+          <i className={iconNameByFormat(attachment.fileFormat)}></i> {attachment.originalName}
+        </p>
+        <p>
+          uploaded by <UserPicture user={attachment.creator} size="sm"></UserPicture> <Username user={attachment.creator}></Username>
+        </p>
+        {content}
+      </div>
+    );
+  }, []);
+
+  let deletingIndicator = <></>;
+  if (deleting) {
+    deletingIndicator = <div className="speeding-wheel-sm"></div>;
+  }
+  if (deleteError) {
+    deletingIndicator = <span>{deleteError}</span>;
+  }
+
+
+  return (
+    <Modal isOpen={isOpen} className="attachment-delete-modal" size="lg" aria-labelledby="contained-modal-title-lg" fade={false}>
+      <ModalHeader tag="h4" toggle={toggle} className="bg-danger text-light">
+        <span id="contained-modal-title-lg">Delete attachment?</span>
+      </ModalHeader>
+      <ModalBody>
+        {renderByFileFormat(attachmentToDelete)}
+      </ModalBody>
+      <ModalFooter>
+        <div className="mr-3 d-inline-block">
+          {deletingIndicator}
+        </div>
+        <Button
+          color="danger"
+          onClick={onDeleteConfirm}
+          disabled={deleting}
+        >Delete!
+        </Button>
+      </ModalFooter>
+    </Modal>
+  );
+
+};

+ 0 - 45
packages/app/src/components/PageAttachment/PageAttachmentList.jsx

@@ -1,45 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-
-import { Attachment } from '@growi/ui';
-
-export default class PageAttachmentList extends React.Component {
-
-  render() {
-    if (this.props.attachments <= 0) {
-      return null;
-    }
-
-    const attachmentList = this.props.attachments.map((attachment, idx) => {
-      return (
-        <Attachment
-          key={`page:attachment:${attachment._id}`}
-          attachment={attachment}
-          inUse={this.props.inUse[attachment._id] || false}
-          onAttachmentDeleteClicked={this.props.onAttachmentDeleteClicked}
-          isUserLoggedIn={this.props.isUserLoggedIn}
-        />
-      );
-    });
-
-    return (
-      <div>
-        <ul className="pl-2">
-          {attachmentList}
-        </ul>
-      </div>
-    );
-  }
-
-}
-
-PageAttachmentList.propTypes = {
-  attachments: PropTypes.arrayOf(PropTypes.object),
-  inUse: PropTypes.objectOf(PropTypes.bool),
-  onAttachmentDeleteClicked: PropTypes.func,
-  isUserLoggedIn: PropTypes.bool,
-};
-PageAttachmentList.defaultProps = {
-  attachments: [],
-  inUse: {},
-};

+ 47 - 0
packages/app/src/components/PageAttachment/PageAttachmentList.tsx

@@ -0,0 +1,47 @@
+import React from 'react';
+
+
+import { HasObjectId, IAttachment } from '@growi/core';
+import { Attachment } from '@growi/ui';
+import { useTranslation } from 'next-i18next';
+
+
+type Props = {
+  attachments: (IAttachment & HasObjectId)[],
+  inUse: { [id: string]: boolean },
+  onAttachmentDeleteClicked?: (attachment: IAttachment & HasObjectId) => void,
+  isUserLoggedIn?: boolean,
+}
+
+export const PageAttachmentList = (props: Props): JSX.Element => {
+  const { t } = useTranslation();
+
+  const {
+    attachments, inUse, onAttachmentDeleteClicked, isUserLoggedIn,
+  } = props;
+
+  if (attachments.length === 0) {
+    return <>{t('No_attachments_yet')}</>;
+  }
+
+  const attachmentList = attachments.map((attachment) => {
+    return (
+      <Attachment
+        key={`page:attachment:${attachment._id}`}
+        attachment={attachment}
+        inUse={inUse[attachment._id] || false}
+        onAttachmentDeleteClicked={onAttachmentDeleteClicked}
+        isUserLoggedIn={isUserLoggedIn}
+      />
+    );
+  });
+
+  return (
+    <div>
+      <ul className="pl-2">
+        {attachmentList}
+      </ul>
+    </div>
+  );
+
+};

+ 7 - 1
packages/app/src/components/PageComment/CommentEditor.tsx

@@ -232,7 +232,13 @@ export const CommentEditor = (props: CommentEditorProps): JSX.Element => {
 
     const errorMessage = <span className="text-danger text-right mr-2">{error}</span>;
     const cancelButton = (
-      <Button outline color="danger" size="xs" className="btn btn-outline-danger rounded-pill" onClick={cancelButtonClickedHandler}>
+      <Button
+        outline
+        color="danger"
+        size="xs"
+        className="btn btn-outline-danger rounded-pill"
+        onClick={cancelButtonClickedHandler}
+      >
         Cancel
       </Button>
     );

+ 5 - 0
packages/app/src/components/PageEditor/CodeMirrorEditor.module.scss

@@ -59,6 +59,11 @@
     pre.CodeMirror-line-like.CodeMirror-placeholder {
       color: bs.$text-muted;
     }
+
+    // overwrite .CodeMirror-scroll
+    .CodeMirror-scroll {
+      box-sizing: border-box;
+    }
   }
 
   // patch to fix https://github.com/codemirror/CodeMirror/issues/4089

+ 117 - 98
packages/app/src/components/PageEditorByHackmd.tsx

@@ -1,47 +1,54 @@
 import React, {
-  useCallback, useEffect, useRef, useState,
+  useCallback, useRef, useState, useEffect,
 } from 'react';
 
+import EventEmitter from 'events';
+
 import { useTranslation } from 'react-i18next';
 
 
-import AppContainer from '~/client/services/AppContainer';
-import PageContainer from '~/client/services/PageContainer';
+import { saveOrUpdate } from '~/client/services/page-operation';
+import { toastError, toastSuccess } from '~/client/util/apiNotification';
 import { apiPost } from '~/client/util/apiv1-client';
 import { getOptionsToSave } from '~/client/util/editor';
 import { IResHackmdIntegrated, IResHackmdDiscard } from '~/interfaces/hackmd';
-import { useCurrentPagePath, useCurrentPageId } from '~/stores/context';
+import {
+  useCurrentPagePath, useCurrentPageId, useHackmdUri, usePageIdOnHackmd, useHasDraftOnHackmd, useRevisionIdHackmdSynced,
+} from '~/stores/context';
 import { useSWRxSlackChannels, useIsSlackEnabled, usePageTagsForEditors } from '~/stores/editor';
+import { useSWRxCurrentPage } from '~/stores/page';
 import {
+  EditorMode,
   useEditorMode, useSelectedGrant,
 } from '~/stores/ui';
 import loggerFactory from '~/utils/logger';
 
 import HackmdEditor from './PageEditorByHackmd/HackmdEditor';
-import { withUnstatedContainers } from './UnstatedUtils';
 
 const logger = loggerFactory('growi:PageEditorByHackmd');
 
-type PageEditorByHackmdProps = {
-  appContainer: AppContainer,
-  pageContainer: PageContainer,
-};
+declare const globalEmitter: EventEmitter;
 
 type HackEditorRef = {
-  getValue: () => string
+  getValue: () => Promise<string>
 };
 
-const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
-  const { appContainer, pageContainer } = props; // wip
+export const PageEditorByHackmd = (): JSX.Element => {
 
   const { t } = useTranslation();
-  const { data: editorMode } = useEditorMode();
+  const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
   const { data: currentPagePath } = useCurrentPagePath();
+  const { data: currentPathname } = useCurrentPagePath();
   const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
   const { data: isSlackEnabled } = useIsSlackEnabled();
   const { data: pageId } = useCurrentPageId();
   const { data: pageTags, mutate: updatePageTagsForEditors } = usePageTagsForEditors(pageId);
   const { data: grant } = useSelectedGrant();
+  const { data: hackmdUri } = useHackmdUri();
+
+  // pageData
+  const { data: pageData, mutate: updatePageData } = useSWRxCurrentPage();
+  const revision = pageData?.revision;
 
   const slackChannels = slackChannelsData?.toString();
 
@@ -52,41 +59,61 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
   const [errorMessage, setErrorMessage] = useState('');
   const [errorReason, setErrorReason] = useState('');
 
+  // state from pageContainer
+  const { data: pageIdOnHackmd, mutate: mutatePageIdOnHackmd } = usePageIdOnHackmd();
+  const { data: hasDraftOnHackmd, mutate: mutateHasDraftOnHackmd } = useHasDraftOnHackmd();
+  const { data: revisionIdHackmdSynced, mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
+  const [isHackmdDraftUpdatingInRealtime, setIsHackmdDraftUpdatingInRealtime] = useState(false);
+  const [remoteRevisionId, setRemoteRevisionId] = useState(revision?._id); // initialize
+
   const hackmdEditorRef = useRef<HackEditorRef>(null);
 
+  const saveAndReturnToViewHandler = useCallback(async(opts?: {overwriteScopesOfDescendants: boolean}) => {
+    if (editorMode !== EditorMode.HackMD) {
+      return;
+    }
+
+    if (isSlackEnabled == null || currentPathname == null || slackChannels == null || grant == null || revision == null || hackmdEditorRef.current == null) {
+      return;
+    }
+
+    let optionsToSave;
+
+    const currentOptionsToSave = getOptionsToSave(
+      isSlackEnabled, slackChannels, grant.grant, grant.grantedGroup?.id, grant.grantedGroup?.name, pageTags ?? [], true,
+    );
+
+    if (opts != null) {
+      optionsToSave = Object.assign(currentOptionsToSave, {
+        ...opts,
+      });
+    }
+    else {
+      optionsToSave = currentOptionsToSave;
+    }
+
+    const markdown = await hackmdEditorRef.current.getValue();
+
+    await saveOrUpdate(optionsToSave, { pageId, path: currentPagePath || currentPathname, revisionId: revision?._id }, markdown);
+    await updatePageData();
+    mutateEditorMode(EditorMode.View);
+  }, [currentPagePath, currentPathname, editorMode, grant, isSlackEnabled, pageId, pageTags, revision, slackChannels, mutateEditorMode, updatePageData]);
+
+  // set handler to save and reload Page
   useEffect(() => {
-    const pageEditorByHackmdInstance = {
-      getMarkdown: () => {
-        if (!isInitialized) {
-          return Promise.reject(new Error(t('hackmd.not_initialized')));
-        }
-
-        if (hackmdEditorRef.current == null) { return }
-
-        return hackmdEditorRef.current.getValue();
-      },
-      reset: () => {
-        setIsInitialized(false);
-      },
-    };
-    // appContainer.registerComponentInstance('PageEditorByHackmd', pageEditorByHackmdInstance);
-  }, [appContainer, isInitialized, t]);
+    globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
 
-  const getHackmdUri = useCallback(() => {
-    const envVars = appContainer.getConfig().env;
-    return envVars.HACKMD_URI;
-  }, [appContainer]);
+    return function cleanup() {
+      globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
+    };
+  }, [saveAndReturnToViewHandler]);
 
   const isResume = useCallback(() => {
-    const {
-      pageIdOnHackmd, hasDraftOnHackmd, isHackmdDraftUpdatingInRealtime,
-    } = pageContainer.state;
     const isPageExistsOnHackmd = (pageIdOnHackmd != null);
     return (isPageExistsOnHackmd && hasDraftOnHackmd) || isHackmdDraftUpdatingInRealtime;
-  }, [pageContainer.state]);
+  }, [hasDraftOnHackmd, isHackmdDraftUpdatingInRealtime, pageIdOnHackmd]);
 
   const startToEdit = useCallback(async() => {
-    const hackmdUri = getHackmdUri();
 
     if (hackmdUri == null) {
       // do nothing
@@ -103,13 +130,11 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
         throw new Error(res.error);
       }
 
-      await pageContainer.setState({
-        pageIdOnHackmd: res.pageIdOnHackmd,
-        revisionIdHackmdSynced: res.revisionIdHackmdSynced,
-      });
+      mutatePageIdOnHackmd(res.pageIdOnHackmd);
+      mutateRevisionIdHackmdSynced(res.revisionIdHackmdSynced);
     }
     catch (err) {
-      pageContainer.showErrorToastr(err);
+      toastError(err);
 
       setHasError(true);
       setErrorMessage('GROWI server failed to connect to HackMD.');
@@ -118,7 +143,7 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
 
     setIsInitialized(true);
     setIsInitializing(false);
-  }, [getHackmdUri, pageContainer, pageId]);
+  }, [pageId, hackmdUri, mutatePageIdOnHackmd, mutateRevisionIdHackmdSynced]);
 
   /**
    * Start to edit w/o any api request
@@ -128,7 +153,8 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
   }, []);
 
   const discardChanges = useCallback(async() => {
-    const { pageId } = pageContainer.state;
+
+    if (pageId == null) { return }
 
     try {
       const res = await apiPost<IResHackmdDiscard>('/hackmd.discard', { pageId });
@@ -137,89 +163,91 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
         throw new Error(res.error);
       }
 
-      pageContainer.setState({
-        isHackmdDraftUpdatingInRealtime: false,
-        hasDraftOnHackmd: false,
-        pageIdOnHackmd: res.pageIdOnHackmd,
-        remoteRevisionId: res.revisionIdHackmdSynced,
-        revisionIdHackmdSynced: res.revisionIdHackmdSynced,
-      });
+      setIsHackmdDraftUpdatingInRealtime(false);
+      mutateHasDraftOnHackmd(false);
+      mutatePageIdOnHackmd(res.pageIdOnHackmd);
+      setRemoteRevisionId(res.revisionIdHackmdSynced);
+      mutateRevisionIdHackmdSynced(res.revisionIdHackmdSynced);
+
+
     }
     catch (err) {
       logger.error(err);
-      pageContainer.showErrorToastr(err);
+      toastError(err);
     }
-  }, [pageContainer]);
+  }, [setIsHackmdDraftUpdatingInRealtime, mutateHasDraftOnHackmd, mutatePageIdOnHackmd, mutateRevisionIdHackmdSynced, pageId]);
 
   /**
    * save and update state of containers
    * @param {string} markdown
    */
   const onSaveWithShortcut = useCallback(async(markdown) => {
-    if (isSlackEnabled == null || grant == null || slackChannels == null) { return }
-    const optionsToSave = getOptionsToSave(isSlackEnabled, slackChannels, grant.grant, grant.grantedGroup?.id, grant.grantedGroup?.name, pageTags ?? []);
+    if (
+      isSlackEnabled == null || grant == null || slackChannels == null || pageId == null || revisionIdHackmdSynced == null || currentPathname == null
+    ) { return }
+    const optionsToSave = getOptionsToSave(
+      isSlackEnabled, slackChannels, grant.grant, grant.grantedGroup?.id, grant.grantedGroup?.name, pageTags ?? [], true,
+    );
 
     try {
-      // disable unsaved warning
-      // editorContainer.disableUnsavedWarning(); commentout because disableUnsavedWarning doesn't exitst
+      const res = await saveOrUpdate(optionsToSave, { pageId, path: currentPagePath || currentPathname, revisionId: revisionIdHackmdSynced }, markdown);
 
-      // eslint-disable-next-line no-unused-vars
-      const { page, tags } = await pageContainer.save(markdown, editorMode, optionsToSave);
-      logger.debug('success to save');
+      // update pageData
+      updatePageData();
 
-      pageContainer.showSuccessToastr();
+      // set updated data
+      setRemoteRevisionId(res.revision._id);
+      mutateRevisionIdHackmdSynced(res.page.revisionHackmdSynced);
+      mutateHasDraftOnHackmd(res.page.hasDraftOnHackmd);
+      updatePageTagsForEditors(res.tags);
 
-      updatePageTagsForEditors(tags);
+      // call reset
+      setIsInitialized(false);
+
+      logger.debug('success to save');
+
+      toastSuccess(t('successfully_saved_the_page'));
     }
     catch (error) {
       logger.error('failed to save', error);
-      pageContainer.showErrorToastr(error);
+      toastError(error);
     }
-  }, [editorMode, grant, isSlackEnabled, pageContainer, pageTags, slackChannels, updatePageTagsForEditors]);
+  }, [
+    grant, isSlackEnabled, pageTags, slackChannels, updatePageTagsForEditors, pageId, currentPagePath, currentPathname,
+    revisionIdHackmdSynced, updatePageData, mutateHasDraftOnHackmd, mutateRevisionIdHackmdSynced, t,
+  ]);
 
   /**
    * onChange event of HackmdEditor handler
    */
   const hackmdEditorChangeHandler = useCallback(async(body) => {
-    const hackmdUri = getHackmdUri();
 
-    if (hackmdUri == null) {
+    if (hackmdUri == null || pageId == null) {
       // do nothing
       return;
     }
 
-    // do nothing if contents are same
-    if (pageContainer.state.markdown === body) {
+    if (revision?.body === body) {
       return;
     }
 
-    // enable unsaved warning
-    // editorContainer.enableUnsavedWarning(); commentout because enableUnsavedWarning doesn't exitst
-
-    const params = {
-      pageId: pageContainer.state.pageId,
-    };
     try {
-      await apiPost('/hackmd.saveOnHackmd', params);
+      await apiPost('/hackmd.saveOnHackmd', { pageId });
     }
     catch (err) {
       logger.error(err);
     }
-  }, [getHackmdUri, pageContainer.state.markdown, pageContainer.state.pageId]);
+  }, [pageId, revision?.body, hackmdUri]);
 
   const penpalErrorOccuredHandler = useCallback((error) => {
-    pageContainer.showErrorToastr(error);
+    toastError(error);
 
     setHasError(true);
     setErrorMessage(t('hackmd.fail_to_connect'));
     setErrorReason(error.toString());
-  }, [pageContainer, t]);
+  }, [t]);
 
   const renderPreInitContent = useCallback(() => {
-    const hackmdUri = getHackmdUri();
-    const {
-      revisionId, revisionIdHackmdSynced, remoteRevisionId, pageId,
-    } = pageContainer.state;
     const isPageNotFound = pageId == null;
 
     let content;
@@ -316,7 +344,7 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
      * Start to edit
      */
     else {
-      const isRevisionOutdated = revisionId !== remoteRevisionId;
+      const isRevisionOutdated = revision?._id !== remoteRevisionId;
 
       content = (
         <div>
@@ -342,30 +370,25 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
         {content}
       </div>
     );
-  }, [discardChanges, getHackmdUri, isInitializing, isResume, pageContainer.state, resumeToEdit, startToEdit, t]);
+  }, [discardChanges, isInitializing, isResume, resumeToEdit, startToEdit, t, hackmdUri, pageId, remoteRevisionId, revisionIdHackmdSynced, revision?._id]);
 
-  if (editorMode == null) {
-    return null;
+  if (editorMode == null || revision == null) {
+    return <></>;
   }
 
-  const hackmdUri = getHackmdUri();
-  const {
-    markdown, pageIdOnHackmd,
-  } = pageContainer.state;
-
   let content;
 
   // TODO: typescriptize
   // using any because ref cann't used between FC and class conponent with type safe
   const AnyEditor = HackmdEditor as any;
 
-  if (isInitialized) {
+  if (isInitialized && hackmdUri != null) {
     content = (
       <AnyEditor
         ref={hackmdEditorRef}
         hackmdUri={hackmdUri}
         pageIdOnHackmd={pageIdOnHackmd}
-        initializationMarkdown={isResume() ? null : markdown}
+        initializationMarkdown={isResume() ? null : revision.body}
         onChange={hackmdEditorChangeHandler}
         onSaveWithShortcut={(document) => {
           onSaveWithShortcut(document);
@@ -403,7 +426,3 @@ const PageEditorByHackmd = (props: PageEditorByHackmdProps) => {
   );
 
 };
-
-const PageEditorByHackmdWrapper = withUnstatedContainers(PageEditorByHackmd, [AppContainer, PageContainer]);
-
-export default PageEditorByHackmdWrapper;

+ 22 - 1
packages/app/src/components/ReactMarkdownComponents/Header.tsx

@@ -1,5 +1,8 @@
+import { useEffect, useState } from 'react';
+
 import EventEmitter from 'events';
 
+import { useRouter } from 'next/router';
 import { Element } from 'react-markdown/lib/rehype-filter';
 
 import { NextLink } from './NextLink';
@@ -48,10 +51,28 @@ export const Header = (props: HeaderProps): JSX.Element => {
     node, id, children, level,
   } = props;
 
+  const router = useRouter();
+
+  const [isActive, setActive] = useState(false);
+
   const CustomTag = `h${level}` as keyof JSX.IntrinsicElements;
 
+  // update isActive when hash is changed
+  useEffect(() => {
+    const handler = (url: string) => {
+      const hash = (new URL(url, 'https://example.com')).hash.slice(1);
+      setActive(hash === id);
+    };
+
+    router.events.on('hashChangeComplete', handler);
+
+    return () => {
+      router.events.off('hashChangeComplete', handler);
+    };
+  }, [id, router.events]);
+
   return (
-    <CustomTag id={id} className={`revision-head ${styles['revision-head']}`}>
+    <CustomTag id={id} className={`revision-head ${styles['revision-head']} ${isActive ? 'blink' : ''}`}>
       {children}
       <NextLink href={`#${id}`} className="revision-head-link">
         <span className="icon-link"></span>

+ 14 - 2
packages/app/src/components/ReactMarkdownComponents/NextLink.tsx

@@ -1,4 +1,5 @@
 import Link, { LinkProps } from 'next/link';
+import { Link as ScrollLink } from 'react-scroll';
 
 import { useSiteUrl } from '~/stores/context';
 
@@ -25,9 +26,20 @@ export const NextLink = ({
 
   const { data: siteUrl } = useSiteUrl();
 
+  if (href == null) {
+    return <a className={className}>{children}</a>;
+  }
+
   // when href is an anchor link
-  if (href == null || isAnchorLink(href)) {
-    return <a href={href} className={className}>{children}</a>;
+  if (isAnchorLink(href)) {
+    const to = href.slice(1);
+    return (
+      <Link href={href} scroll={false}>
+        <ScrollLink href={href} to={to} className={className} smooth="easeOutQuart" offset={-100} duration={800}>
+          {children}
+        </ScrollLink>
+      </Link>
+    );
   }
 
   if (isExternalLink(href, siteUrl)) {

+ 2 - 5
packages/app/src/components/SavePageControls.tsx

@@ -59,7 +59,7 @@ export const SavePageControls = (props: Props): JSX.Element | null => {
   }, [mutateIsEnabledUnsavedWarning]);
 
 
-  if (isEditable == null || isAclEnabled == null) {
+  if (isEditable == null || isAclEnabled == null || grantData == null) {
     return null;
   }
 
@@ -67,10 +67,7 @@ export const SavePageControls = (props: Props): JSX.Element | null => {
     return null;
   }
 
-  const grant = grantData?.grant || PageGrant.GRANT_PUBLIC;
-  const grantedGroup = grantData?.grantedGroup;
-
-  // const {  pageContainer } = props;
+  const { grant, grantedGroup } = grantData;
 
   const isRootPage = isTopPage(currentPagePath ?? '');
   const labelSubmitButton = pageId == null ? t('Create') : t('Update');

+ 5 - 9
packages/app/src/components/ShareLink/ShareLinkForm.tsx

@@ -1,7 +1,9 @@
 import React, { FC, useState, useCallback } from 'react';
 
 import { isInteger } from 'core-js/fn/number';
-import { format, parse } from 'date-fns';
+import {
+  format, parse, addDays, set,
+} from 'date-fns';
 import { useTranslation } from 'next-i18next';
 
 import { toastSuccess, toastError } from '~/client/util/apiNotification';
@@ -56,8 +58,6 @@ export const ShareLinkForm: FC<Props> = (props: Props) => {
   }, []);
 
   const generateExpired = useCallback(() => {
-    let expiredAt;
-
     if (expirationType === ExpirationType.UNLIMITED) {
       return null;
     }
@@ -66,16 +66,12 @@ export const ShareLinkForm: FC<Props> = (props: Props) => {
       if (!isInteger(Number(numberOfDays))) {
         throw new Error(t('share_links.Invalid_Number_of_Date'));
       }
-      const date = new Date();
-      date.setDate(date.getDate() + Number(numberOfDays));
-      expiredAt = date;
+      return addDays(new Date(), numberOfDays);
     }
 
     if (expirationType === ExpirationType.CUSTOM) {
-      expiredAt = parse(`${customExpirationDate}T${customExpirationTime}`, "yyyy-MM-dd'T'HH:mm", new Date());
+      return set(customExpirationDate, { hours: customExpirationTime.getHours(), minutes: customExpirationTime.getMinutes() });
     }
-
-    return expiredAt;
   }, [t, customExpirationTime, customExpirationDate, expirationType, numberOfDays]);
 
   const closeForm = useCallback(() => {

+ 4 - 1
packages/app/src/components/TableOfContents.module.scss

@@ -9,6 +9,10 @@
   border-bottom: 1px solid transparent;
 
   .revision-toc-content {
+    ul {
+      list-style-type: disc;
+    }
+
     li {
       margin: 6px;
     }
@@ -22,7 +26,6 @@
     // first level of li
     > ul > li {
       padding: 5px;
-      margin-right: 4px;
       margin-left: 17px;
     }
   }

+ 2 - 11
packages/app/src/components/TableOfContents.tsx

@@ -1,9 +1,7 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { useCallback } from 'react';
 
 import ReactMarkdown from 'react-markdown';
 
-import { blinkElem } from '~/client/util/blink-section-header';
-import { addSmoothScrollEvent } from '~/client/util/smooth-scroll';
 import { useIsUserPage } from '~/stores/context';
 import { useTocOptions } from '~/stores/renderer';
 import loggerFactory from '~/utils/logger';
@@ -22,7 +20,7 @@ const TableOfContents = (): JSX.Element => {
 
   const { data: isUserPage } = useIsUserPage();
 
-  const [tocHtml, setTocHtml] = useState('');
+  // const [tocHtml, setTocHtml] = useState('');
 
   const { data: rendererOptions } = useTocOptions();
 
@@ -49,13 +47,6 @@ const TableOfContents = (): JSX.Element => {
     return bottom - (containerTop + containerPaddingTop);
   }, [isUserPage]);
 
-  useEffect(() => {
-    const tocDom = document.getElementById('revision-toc-content');
-    if (tocDom == null) { return }
-    const anchorsInToc = Array.from(tocDom.getElementsByTagName('a'));
-    addSmoothScrollEvent(anchorsInToc, blinkElem);
-  }, [tocHtml]);
-
   return (
     <div id="revision-toc" className={`revision-toc ${styles['revision-toc']}`}>
       <StickyStretchableScroller

+ 22 - 0
packages/app/src/components/User/SeenUserInfo.module.scss

@@ -0,0 +1,22 @@
+@use '~/styles/bootstrap/init' as bs;
+@use '~/styles/mixins';
+
+.grw-seen-user-info :global {
+  .btn.btn-seen-user {
+    $color-seen-user: #549c79;
+
+    @include bs.button-outline-variant($color-seen-user, $color-seen-user, rgba(lighten($color-seen-user, 10%), 0.15), rgba(lighten($color-seen-user, 10%), 0.5));
+    @include mixins.button-outline-svg-icon-variant($color-seen-user, $color-seen-user);
+
+    &:not(:disabled):not(.disabled):active,
+    &:not(:disabled):not(.disabled).active {
+      color: $color-seen-user;
+      svg {
+        fill: $color-seen-user;
+      }
+    }
+    &:not(:disabled):not(.disabled):not(:hover) {
+      background-color: transparent;
+    }
+  }
+}

+ 5 - 1
packages/app/src/components/User/SeenUserInfo.tsx

@@ -8,6 +8,10 @@ import { IUser } from '~/interfaces/user';
 
 import UserPictureList from './UserPictureList';
 
+
+import styles from './SeenUserInfo.module.scss';
+
+
 interface Props {
   seenUsers: IUser[],
   sumOfSeenUsers?: number,
@@ -23,7 +27,7 @@ const SeenUserInfo: FC<Props> = (props: Props) => {
   const togglePopover = () => setIsPopoverOpen(!isPopoverOpen);
 
   return (
-    <div className="grw-seen-user-info">
+    <div className={`grw-seen-user-info ${styles['grw-seen-user-info']}`}>
       <button type="button" id="btn-seen-user" className="shadow-none btn btn-seen-user border-0">
         <span className="mr-1 footstamp-icon">
           <FootstampIcon />

+ 4 - 9
packages/app/src/components/User/UserInfo.tsx

@@ -2,20 +2,15 @@ import React from 'react';
 
 import { UserPicture } from '@growi/ui';
 
-import { IUserHasId } from '~/interfaces/user';
+import { usePageUser } from '~/stores/context';
 
 import styles from './UserInfo.module.scss';
 
-export type UserInfoProps = {
-  pageUser: IUserHasId,
-}
+export const UserInfo = (): JSX.Element => {
 
-export const UserInfo = (props: UserInfoProps): JSX.Element => {
+  const { data: pageUser } = usePageUser();
 
-  const { pageUser } = props;
-
-  // Do not display when the user does not exist
-  if (pageUser == null) {
+  if (pageUser == null || pageUser.status === 4) {
     return <></>;
   }
 

+ 2 - 4
packages/app/src/interfaces/attachment.ts

@@ -1,10 +1,8 @@
-import type { IAttachment } from '@growi/core';
+import type { HasObjectId, IAttachment } from '@growi/core';
 
 import type { PaginateResult } from './mongoose-utils';
 
 
 export type IResAttachmentList = {
-  data: {
-    paginateResult: PaginateResult<IAttachment>
-  }
+  paginateResult: PaginateResult<IAttachment & HasObjectId>
 };

+ 1 - 0
packages/app/src/interfaces/editor-settings.ts

@@ -43,4 +43,5 @@ export type OptionsToSave = {
   pageTags: string[] | null;
   grantUserGroupId?: string | null;
   grantUserGroupName?: string | null;
+  isSyncRevisionToHackmd?: boolean;
 };

+ 11 - 0
packages/app/src/interfaces/share-link.ts

@@ -1,4 +1,15 @@
+import { IPageHasId, HasObjectId } from '@growi/core';
+
 // Todo: specify more detailed Type
 export type IResShareLinkList = {
   shareLinksResult: any[],
 };
+
+export type IShareLink = {
+  relatedPage: IPageHasId,
+  createdAt: Date,
+  expiredAt?: Date,
+  description: string,
+};
+
+export type IShareLinkHasId = IShareLink & HasObjectId;

+ 2 - 1
packages/app/src/pages/admin/[[...path]].page.tsx

@@ -307,7 +307,8 @@ async function injectServerConfigurations(context: GetServerSidePropsContext, pr
  * @param namespacesRequired
  */
 async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
-  const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
+  // preload all languages because of language lists in user setting
+  const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired, true);
   props._nextI18Next = nextI18NextConfig._nextI18Next;
 }
 

+ 26 - 6
packages/app/src/pages/login.page.tsx

@@ -4,9 +4,10 @@ import React from 'react';
 import {
   NextPage, GetServerSideProps, GetServerSidePropsContext,
 } from 'next';
-import dynamic from 'next/dynamic';
+import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
 
 import { NoLoginLayout } from '~/components/Layout/NoLoginLayout';
+import { LoginForm } from '~/components/LoginForm';
 import { CrowiRequest } from '~/interfaces/crowi-request';
 
 import {
@@ -16,11 +17,9 @@ import {
 
 
 import {
-  CommonProps, getServerSideCommonProps, useCustomTitle,
+  CommonProps, getServerSideCommonProps, useCustomTitle, getNextI18NextConfig,
 } from './utils/commons';
 
-const LoginForm = dynamic(() => import('~/components/LoginForm'), { ssr: false });
-
 type Props = CommonProps & {
 
   pageWithMetaStr: string,
@@ -41,12 +40,32 @@ const LoginPage: NextPage<Props> = (props: Props) => {
 
   return (
     <NoLoginLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
-      <LoginForm objOfIsExternalAuthEnableds={props.enabledStrategies} isLocalStrategySetup={true} isLdapStrategySetup={true}
-        isRegistrationEnabled={true} registrationWhiteList={props.registrationWhiteList} isPasswordResetEnabled={true} />
+      <LoginForm
+        // Todo: These props should be set properly. https://redmine.weseek.co.jp/issues/104847
+        objOfIsExternalAuthEnableds={props.enabledStrategies}
+        isLocalStrategySetup={true}
+        isLdapStrategySetup={true}
+        isEmailAuthenticationEnabled={false}
+        isRegistrationEnabled={true}
+        registrationWhiteList={props.registrationWhiteList}
+        isPasswordResetEnabled={true}
+        isMailerSetup={false}
+      />
     </NoLoginLayout>
   );
 };
 
+/**
+ * for Server Side Translations
+ * @param context
+ * @param props
+ * @param namespacesRequired
+ */
+async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
+  const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
+  props._nextI18Next = nextI18NextConfig._nextI18Next;
+}
+
 function injectEnabledStrategies(context: GetServerSidePropsContext, props: Props): void {
   const req: CrowiRequest = context.req as CrowiRequest;
   const { crowi } = req;
@@ -92,6 +111,7 @@ export const getServerSideProps: GetServerSideProps = async(context: GetServerSi
 
   injectServerConfigurations(context, props);
   injectEnabledStrategies(context, props);
+  await injectNextI18NextConfigurations(context, props, ['translation']);
 
   return {
     props,

+ 2 - 1
packages/app/src/pages/me/[[...path]].page.tsx

@@ -169,7 +169,8 @@ async function injectServerConfigurations(context: GetServerSidePropsContext, pr
 //  * @param namespacesRequired
 //  */
 async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
-  const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
+  // preload all languages because of language lists in user setting
+  const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired, true);
   props._nextI18Next = nextI18NextConfig._nextI18Next;
 }
 

+ 169 - 0
packages/app/src/pages/share/[[...path]].page.tsx

@@ -0,0 +1,169 @@
+import React from 'react';
+
+import { IUser, IUserHasId } from '@growi/core';
+import {
+  NextPage, GetServerSideProps, GetServerSidePropsContext,
+} from 'next';
+import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
+import dynamic from 'next/dynamic';
+
+import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
+import GrowiContextualSubNavigation from '~/components/Navbar/GrowiContextualSubNavigation';
+import { Page } from '~/components/Page';
+import { CrowiRequest } from '~/interfaces/crowi-request';
+import { RendererConfig } from '~/interfaces/services/renderer';
+import { IShareLinkHasId } from '~/interfaces/share-link';
+import {
+  useCurrentUser, useCurrentPagePath, useCurrentPathname, useCurrentPageId, useRendererConfig,
+  useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault,
+} from '~/stores/context';
+
+import {
+  CommonProps, getServerSideCommonProps, useCustomTitle, getNextI18NextConfig,
+} from '../utils/commons';
+
+const ShareLinkAlert = dynamic(() => import('~/components/Page/ShareLinkAlert'), { ssr: false });
+const ForbiddenPage = dynamic(() => import('~/components/ForbiddenPage'), { ssr: false });
+
+type Props = CommonProps & {
+  shareLink?: IShareLinkHasId,
+  isExpired: boolean,
+  currentUser: IUser,
+  disableLinkSharing: boolean,
+  isSearchServiceConfigured: boolean,
+  isSearchServiceReachable: boolean,
+  isSearchScopeChildrenAsDefault: boolean,
+  rendererConfig: RendererConfig,
+};
+
+const SharedPage: NextPage<Props> = (props: Props) => {
+  useShareLinkId(props.shareLink?._id);
+  useCurrentPageId(props.shareLink?.relatedPage._id);
+  useCurrentPagePath(props.shareLink?.relatedPage.path);
+  useCurrentUser(props.currentUser);
+  useCurrentPathname(props.currentPathname);
+  useRendererConfig(props.rendererConfig);
+  useIsSearchServiceConfigured(props.isSearchServiceConfigured);
+  useIsSearchServiceReachable(props.isSearchServiceReachable);
+  useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
+
+  const isNotFound = props.shareLink == null || props.shareLink.relatedPage == null || props.shareLink.relatedPage.isEmpty;
+  const isShowSharedPage = !props.disableLinkSharing && !isNotFound && !props.isExpired;
+
+  return (
+    <ShareLinkLayout title={useCustomTitle(props, 'GROWI')} expandContainer={props.isContainerFluid}>
+      <div className="h-100 d-flex flex-column justify-content-between">
+        <header className="py-0 position-relative">
+          {isShowSharedPage && <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />}
+        </header>
+
+        <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
+
+        <div className="flex-grow-1">
+          <div id="content-main" className="content-main grw-container-convertible">
+            { props.disableLinkSharing && (
+              <div className="mt-4">
+                <ForbiddenPage isLinkSharingDisabled={props.disableLinkSharing} />
+              </div>
+            )}
+
+            { (isNotFound && !props.disableLinkSharing) && (
+              <div className="container-lg">
+                <h2 className="text-muted mt-4">
+                  <i className="icon-ban" aria-hidden="true" />
+                  <span> Page is not found</span>
+                </h2>
+              </div>
+            )}
+
+            { (props.isExpired && !props.disableLinkSharing) && (
+              <div className="container-lg">
+                <h2 className="text-muted mt-4">
+                  <i className="icon-ban" aria-hidden="true" />
+                  <span> Page is expired</span>
+                </h2>
+              </div>
+            )}
+
+            {(isShowSharedPage && props.shareLink != null) && (
+              <>
+                <ShareLinkAlert expiredAt={props.shareLink.expiredAt} createdAt={props.shareLink.createdAt} />
+                <Page />
+              </>
+            )}
+          </div>
+        </div>
+      </div>
+    </ShareLinkLayout>
+  );
+};
+
+function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
+  const req: CrowiRequest = context.req as CrowiRequest;
+  const { crowi } = req;
+
+  props.disableLinkSharing = crowi.configManager.getConfig('crowi', 'security:disableLinkSharing');
+
+  props.isSearchServiceConfigured = crowi.searchService.isConfigured;
+  props.isSearchServiceReachable = crowi.searchService.isReachable;
+  props.isSearchScopeChildrenAsDefault = crowi.configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
+
+  props.rendererConfig = {
+    isEnabledLinebreaks: crowi.configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
+    isEnabledLinebreaksInComments: crowi.configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
+    adminPreferredIndentSize: crowi.configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
+    isIndentSizeForced: crowi.configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
+
+    plantumlUri: process.env.PLANTUML_URI ?? null,
+    blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
+
+    // XSS Options
+    isEnabledXssPrevention: crowi.configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
+    attrWhiteList: crowi.xssService.getAttrWhiteList(),
+    tagWhiteList: crowi.xssService.getTagWhiteList(),
+    highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
+  };
+}
+
+async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
+  const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
+  props._nextI18Next = nextI18NextConfig._nextI18Next;
+}
+
+export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
+  const req = context.req as CrowiRequest<IUserHasId & any>;
+  const { user, crowi } = req;
+  const result = await getServerSideCommonProps(context);
+
+  if (!('props' in result)) {
+    throw new Error('invalid getSSP result');
+  }
+  const props: Props = result.props as Props;
+
+  if (user != null) {
+    props.currentUser = user.toObject();
+  }
+
+  const { linkId } = req.params;
+  try {
+    const ShareLinkModel = crowi.model('ShareLink');
+    const shareLink = await ShareLinkModel.findOne({ _id: linkId }).populate('relatedPage');
+    if (shareLink != null) {
+      props.isExpired = shareLink.isExpired();
+      props.shareLink = shareLink.toObject();
+    }
+  }
+  catch (err) {
+    //
+  }
+
+  injectServerConfigurations(context, props);
+  // await injectUserUISettings(context, props);
+  await injectNextI18NextConfigurations(context, props);
+
+  return {
+    props,
+  };
+};
+
+export default SharedPage;

+ 5 - 2
packages/app/src/pages/tags.page.tsx

@@ -5,10 +5,9 @@ import {
 } from '@growi/core';
 import { NextPage, GetServerSideProps, GetServerSidePropsContext } from 'next';
 import { useTranslation } from 'next-i18next';
+import dynamic from 'next/dynamic';
 import Head from 'next/head';
 
-import TagCloudBox from '~/components/TagCloudBox';
-import TagList from '~/components/TagList';
 import { CrowiRequest } from '~/interfaces/crowi-request';
 import { IDataTagCount } from '~/interfaces/tag';
 import { IUserUISettings } from '~/interfaces/user-ui-settings';
@@ -36,6 +35,9 @@ type Props = CommonProps & {
   userUISettings?: IUserUISettings
 };
 
+const TagList = dynamic(() => import('~/components/TagList'), { ssr: false });
+const TagCloudBox = dynamic(() => import('~/components/TagCloudBox'), { ssr: false });
+
 const TagPage: NextPage<CommonProps> = (props: Props) => {
   const [activePage, setActivePage] = useState<number>(1);
   const [offset, setOffset] = useState<number>(0);
@@ -85,6 +87,7 @@ const TagPage: NextPage<CommonProps> = (props: Props) => {
               </div>
             )
           }
+          <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
         </div>
       </BasicLayout>
     </>

+ 6 - 4
packages/app/src/pages/utils/commons.ts

@@ -1,4 +1,4 @@
-import { DevidedPagePath, Lang } from '@growi/core';
+import { DevidedPagePath, Lang, AllLang } from '@growi/core';
 import { GetServerSideProps, GetServerSidePropsContext } from 'next';
 import { SSRConfig, UserConfig } from 'next-i18next';
 
@@ -61,8 +61,10 @@ export const getServerSideCommonProps: GetServerSideProps<CommonProps> = async(c
 export const getNextI18NextConfig = async(
     // 'serverSideTranslations' method should be given from Next.js Page
     //  because importing it in this file causes https://github.com/isaachinman/next-i18next/issues/1545
-    serverSideTranslations: (initialLocale: string, namespacesRequired?: string[] | undefined, configOverride?: UserConfig | null) => Promise<SSRConfig>,
-    context: GetServerSidePropsContext, namespacesRequired?: string[] | undefined,
+    serverSideTranslations: (
+      initialLocale: string, namespacesRequired?: string[] | undefined, configOverride?: UserConfig | null, extraLocales?: string[] | false
+    ) => Promise<SSRConfig>,
+    context: GetServerSidePropsContext, namespacesRequired?: string[] | undefined, preloadAllLang = false,
 ): Promise<SSRConfig> => {
 
   const req: CrowiRequest = context.req as CrowiRequest;
@@ -74,7 +76,7 @@ export const getNextI18NextConfig = async(
     ?? configManager.getConfig('crowi', 'app:globalLang') as Lang
     ?? Lang.en_US;
 
-  return serverSideTranslations(locale, namespacesRequired ?? ['translation'], nextI18NextConfig);
+  return serverSideTranslations(locale, namespacesRequired ?? ['translation'], nextI18NextConfig, preloadAllLang ? AllLang : false);
 };
 
 /**

+ 7 - 0
packages/app/src/server/crowi/express-init.js

@@ -170,4 +170,11 @@ module.exports = function(crowi, app) {
   app.use(middlewares.swigFunctions());
 
   // app.use(i18nMiddleware.handle(i18next));
+  // TODO: Remove this workaround implementation when i18n works correctly.
+  //       For now, req.t returns string given to req.t(string)
+  app.use((req, res, next) => {
+    req.t = str => (typeof str === 'string' ? str : '');
+
+    next();
+  });
 };

+ 2 - 2
packages/app/src/server/middlewares/register-form-validator.ts

@@ -13,9 +13,9 @@ export const registerRules = () => {
     body('registerForm.name').not().isEmpty().withMessage('Name field is required'),
     body('registerForm.email')
       .isEmail()
-      .withMessage('Email format is invalid.')
+      .withMessage('Email format is invalid')
       .exists()
-      .withMessage('Email field is required.'),
+      .withMessage('Email field is required'),
     body('registerForm.password')
       .matches(/^[\x20-\x7F]*$/)
       .withMessage('Password has invalid character')

+ 15 - 1
packages/app/src/server/routes/apiv3/index.js

@@ -1,6 +1,8 @@
 import loggerFactory from '~/utils/logger';
 
+import { generateAddActivityMiddleware } from '../../middlewares/add-activity';
 import injectUserRegistrationOrderByTokenMiddleware from '../../middlewares/inject-user-registration-order-by-token-middleware';
+import * as registerFormValidator from '../../middlewares/register-form-validator';
 
 import pageListing from './page-listing';
 import * as userActivation from './user-activation';
@@ -13,7 +15,7 @@ const router = express.Router();
 const routerForAdmin = express.Router();
 const routerForAuth = express.Router();
 
-module.exports = (crowi) => {
+module.exports = (crowi, app, isInstalled) => {
 
   // add custom functions to express response
   require('./response')(express, crowi);
@@ -38,8 +40,20 @@ module.exports = (crowi) => {
   routerForAdmin.use('/activity', require('./activity')(crowi));
 
   // auth
+  const applicationInstalled = require('../../middlewares/application-installed')(crowi);
+  const addActivity = generateAddActivityMiddleware(crowi);
+  const login = require('../login')(crowi, app);
+
   routerForAuth.use('/logout', require('./logout')(crowi));
 
+  routerForAuth.post('/register',
+    applicationInstalled, registerFormValidator.registerRules(), registerFormValidator.registerValidation, addActivity, login.register);
+
+  // installer
+  if (!isInstalled) {
+    routerForAdmin.use('/installer', require('./installer')(crowi));
+    return [router, routerForAdmin, routerForAuth];
+  }
 
   router.use('/in-app-notification', require('./in-app-notification')(crowi));
 

+ 76 - 0
packages/app/src/server/routes/apiv3/installer.ts

@@ -0,0 +1,76 @@
+import express, { Request, Router } from 'express';
+
+import { SupportedAction } from '~/interfaces/activity';
+import ErrorV3 from '~/server/models/vo/error-apiv3';
+import loggerFactory from '~/utils/logger';
+
+import Crowi from '../../crowi';
+import { generateAddActivityMiddleware } from '../../middlewares/add-activity';
+import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
+import { registerRules } from '../../middlewares/register-form-validator';
+import { InstallerService, FailedToCreateAdminUserError } from '../../service/installer';
+
+import { ApiV3Response } from './interfaces/apiv3-response';
+
+
+const logger = loggerFactory('growi:routes:apiv3:installer');
+
+
+type FormRequest = Request & { form: any, logIn: any };
+
+module.exports = (crowi: Crowi): Router => {
+  const addActivity = generateAddActivityMiddleware(crowi);
+
+  const activityEvent = crowi.event('activity');
+
+  const router = express.Router();
+
+  // eslint-disable-next-line max-len
+  router.post('/', registerRules(), apiV3FormValidator, addActivity, async(req: FormRequest, res: ApiV3Response) => {
+    const appService = crowi.appService;
+    if (appService == null) {
+      return res.apiv3Err(new ErrorV3('GROWI cannot be installed due to an internal error', 'app_service_not_setup'), 500);
+    }
+    const registerForm = req.body.registerForm || {};
+
+    const name = registerForm.name;
+    const username = registerForm.username;
+    const email = registerForm.email;
+    const password = registerForm.password;
+    const language = registerForm['app:globalLang'] || 'en_US';
+
+    const installerService = new InstallerService(crowi);
+
+    let adminUser;
+    try {
+      adminUser = await installerService.install({
+        name,
+        username,
+        email,
+        password,
+      }, language);
+    }
+    catch (err) {
+      if (err instanceof FailedToCreateAdminUserError) {
+        return res.apiv3Err(new ErrorV3(err.message, 'failed_to_create_admin_user'));
+      }
+      return res.apiv3Err(new ErrorV3(err, 'failed_to_install'));
+    }
+
+    await appService.setupAfterInstall();
+
+    const parameters = { action: SupportedAction.ACTION_USER_REGISTRATION_SUCCESS };
+    activityEvent.emit('update', res.locals.activity._id, parameters);
+
+    // login with passport
+    req.logIn(adminUser, (err) => {
+      if (err != null) {
+        return res.apiv3Err(new ErrorV3(err, 'failed_to_login_after_install'));
+      }
+
+      return res.apiv3({ message: 'Installation completed (Logged in as an admin user)' });
+    });
+  });
+
+  return router;
+};

+ 3 - 6
packages/app/src/server/routes/index.js

@@ -61,9 +61,9 @@ module.exports = function(crowi, app) {
 
   /* eslint-disable max-len, comma-spacing, no-multi-spaces */
 
-  const [apiV3Router, apiV3AdminRouter, apiV3AuthRouter] = require('./apiv3')(crowi);
+  const [apiV3Router, apiV3AdminRouter, apiV3AuthRouter] = require('./apiv3')(crowi, app, isInstalled);
 
-  app.use('/api-docs', require('./apiv3/docs')(crowi));
+  app.use('/api-docs', require('./apiv3/docs')(crowi, app));
 
   // Rate limiter
   app.use(rateLimiter);
@@ -84,7 +84,6 @@ module.exports = function(crowi, app) {
   app.post('/invited/activateInvited' , applicationInstalled, loginFormValidator.inviteRules(), loginFormValidator.inviteValidation, csrfProtection, login.invited);
   app.post('/login'                   , applicationInstalled, loginFormValidator.loginRules(), loginFormValidator.loginValidation, csrfProtection,  addActivity, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.loginFailure);
 
-  app.post('/register'                , applicationInstalled, registerFormValidator.registerRules(), registerFormValidator.registerValidation, csrfProtection, addActivity, login.register);
   app.get('/register'                 , applicationInstalled, login.preLogin, login.register);
 
   app.get('/admin/*'                    , applicationInstalled, loginRequiredStrictly , adminRequired , next.delegateToNext);
@@ -93,9 +92,7 @@ module.exports = function(crowi, app) {
 
   // installer
   if (!isInstalled) {
-    const installer = require('./installer')(crowi);
     app.get('/installer'              , applicationNotInstalled, next.delegateToNext);
-    app.post('/installer'             , applicationNotInstalled , registerFormValidator.registerRules(), registerFormValidator.registerValidation, csrfProtection, addActivity, installer.install);
     return;
   }
 
@@ -245,7 +242,7 @@ module.exports = function(crowi, app) {
     .use(userActivation.tokenErrorHandlerMiddeware));
   app.post('/user-activation/register', applicationInstalled, csrfProtection, userActivation.registerRules(), userActivation.validateRegisterForm, userActivation.registerAction(crowi));
 
-  app.get('/share/:linkId', page.showSharedPage);
+  app.get('/share/:linkId', next.delegateToNext);
 
   app.use('/ogp', express.Router().get('/:pageId([0-9a-z]{0,})', loginRequired, ogp.pageIdRequired, ogp.ogpValidator, ogp.renderOgp));
 

+ 0 - 70
packages/app/src/server/routes/installer.js

@@ -1,70 +0,0 @@
-import { SupportedAction } from '~/interfaces/activity';
-import loggerFactory from '~/utils/logger';
-
-import { InstallerService, FailedToCreateAdminUserError } from '../service/installer';
-
-const logger = loggerFactory('growi:routes:installer');
-
-module.exports = function(crowi) {
-
-  const actions = {};
-
-  const activityEvent = crowi.event('activity');
-
-  actions.index = function(req, res) {
-    return res.render('installer');
-  };
-
-  actions.install = async function(req, res, next) {
-    const registerForm = req.body.registerForm || {};
-
-    if (!req.form.isValid) {
-      return res.render('installer');
-    }
-
-    const name = registerForm.name;
-    const username = registerForm.username;
-    const email = registerForm.email;
-    const password = registerForm.password;
-    const language = registerForm['app:globalLang'] || 'en_US';
-
-    const installerService = new InstallerService(crowi);
-
-    let adminUser;
-    try {
-      adminUser = await installerService.install({
-        name,
-        username,
-        email,
-        password,
-      }, language);
-    }
-    catch (err) {
-      if (err instanceof FailedToCreateAdminUserError) {
-        req.form.errors.push(req.t('message.failed_to_create_admin_user', { errMessage: err.message }));
-      }
-      return res.render('installer');
-    }
-
-    const appService = crowi.appService;
-    appService.setupAfterInstall();
-
-    // login with passport
-    req.logIn(adminUser, (err) => {
-      if (err) {
-        req.flash('successMessage', req.t('message.complete_to_install1'));
-        req.session.redirectTo = '/';
-        return res.redirect('/login');
-      }
-
-      req.flash('successMessage', req.t('message.complete_to_install2'));
-
-      const parameters = { action: SupportedAction.ACTION_USER_REGISTRATION_SUCCESS };
-      activityEvent.emit('update', res.locals.activity._id, parameters);
-
-      return res.redirect('/');
-    });
-  };
-
-  return actions;
-};

+ 73 - 85
packages/app/src/server/routes/login.js

@@ -19,22 +19,15 @@ module.exports = function(crowi, app) {
     req.login(userData, (err) => {
       if (err) {
         logger.debug(err);
-        // I created a flash message in case the user information that processing was successful is not stored in the session.
-        req.flash('successMessage', req.t('message.successfully_created', { username: userData.username }));
       }
       else {
         // update lastLoginAt
-        userData.updateLastLoginAt(new Date(), (err, userData) => {
+        userData.updateLastLoginAt(new Date(), (err) => {
           if (err) {
             logger.error(`updateLastLoginAt dumps error: ${err}`);
           }
         });
       }
-      // RegisterFormValidator.registerRule had code to guarantee that there was a password,
-      // but login.register did not. so I wrote this code.
-      if (!userData.password) {
-        return res.redirect('/me#password');
-      }
 
       const { redirectTo } = req.session;
       // remove session.redirectTo
@@ -43,10 +36,36 @@ module.exports = function(crowi, app) {
       const parameters = { action: SupportedAction.ACTION_USER_REGISTRATION_SUCCESS };
       activityEvent.emit('update', res.locals.activity._id, parameters);
 
-      return res.safeRedirect(redirectTo);
+      return res.apiv3({ redirectTo });
     });
   };
 
+  async function sendEmailToAllAdmins(userData) {
+    // send mails to all admin users (derived from crowi) -- 2020.06.18 Yuki Takei
+    const admins = await User.findAdmins();
+
+    const appTitle = appService.getAppTitle();
+
+    const promises = admins.map((admin) => {
+      return mailService.send({
+        to: admin.email,
+        subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
+        template: path.join(crowi.localeDir, 'en_US/admin/userWaitingActivation.txt'),
+        vars: {
+          createdUser: userData,
+          admin,
+          url: appService.getSiteUrl(),
+          appTitle,
+        },
+      });
+    });
+
+    const results = await Promise.allSettled(promises);
+    results
+      .filter(result => result.status === 'rejected')
+      .forEach(result => logger.error(result.reason));
+  }
+
   actions.error = function(req, res) {
     const reason = req.params.reason;
 
@@ -93,97 +112,66 @@ module.exports = function(crowi, app) {
 
   actions.register = function(req, res) {
     if (req.user != null) {
-      return res.redirect('/');
+      return res.apiv3Err('user_already_logged_in', 403);
     }
 
     // config で closed ならさよなら
     if (configManager.getConfig('crowi', 'security:registrationMode') === aclService.labels.SECURITY_REGISTRATION_MODE_CLOSED) {
-      return res.redirect('/');
+      return res.apiv3Err('registration_closed', 403);
     }
 
-    if (req.method === 'POST' && req.form.isValid) {
-      const registerForm = req.form.registerForm || {};
-
-      const name = registerForm.name;
-      const username = registerForm.username;
-      const email = registerForm.email;
-      const password = registerForm.password;
-
-      // email と username の unique チェックする
-      User.isRegisterable(email, username, (isRegisterable, errOn) => {
-        let isError = false;
-        if (!User.isEmailValid(email)) {
-          isError = true;
-          req.flash('registerWarningMessage', req.t('message.email_address_could_not_be_used'));
-        }
-        if (!isRegisterable) {
-          if (!errOn.username) {
-            isError = true;
-            req.flash('registerWarningMessage', req.t('message.user_id_is_not_available'));
-          }
-          if (!errOn.email) {
-            isError = true;
-            req.flash('registerWarningMessage', req.t('message.email_address_is_already_registered'));
-          }
+    if (!req.form.isValid) {
+      const errors = req.form.errors;
+      return res.apiv3Err(errors, 401);
+    }
+
+    const registerForm = req.form.registerForm || {};
+
+    const name = registerForm.name;
+    const username = registerForm.username;
+    const email = registerForm.email;
+    const password = registerForm.password;
+
+    // email と username の unique チェックする
+    User.isRegisterable(email, username, (isRegisterable, errOn) => {
+      const errors = [];
+      if (!User.isEmailValid(email)) {
+        errors.push('email_address_could_not_be_used');
+      }
+      if (!isRegisterable) {
+        if (!errOn.username) {
+          errors.push('user_id_is_not_available');
         }
-        if (isError) {
-          debug('isError user register error', errOn);
-          return res.redirect('/register');
+        if (!errOn.email) {
+          errors.push('email_address_is_already_registered');
         }
+      }
+      if (errors.length > 0) {
+        debug('isError user register error', errOn);
+        return res.apiv3Err(errors, 400);
+      }
 
-        User.createUserByEmailAndPassword(name, username, email, password, undefined, async(err, userData) => {
-          if (err) {
-            if (err.name === 'UserUpperLimitException') {
-              req.flash('registerWarningMessage', req.t('message.can_not_register_maximum_number_of_users'));
-            }
-            else {
-              req.flash('registerWarningMessage', req.t('message.failed_to_register'));
-            }
-            return res.redirect('/register');
+      User.createUserByEmailAndPassword(name, username, email, password, undefined, async(err, userData) => {
+        if (err) {
+          const errors = [];
+          if (err.name === 'UserUpperLimitException') {
+            errors.push('can_not_register_maximum_number_of_users');
           }
-
-          if (configManager.getConfig('crowi', 'security:registrationMode') !== aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED) {
-            // send mail asynchronous
-            sendEmailToAllAdmins(userData);
+          else {
+            errors.push('failed_to_register');
           }
+          return res.apiv3Err(errors, 405);
+        }
 
+        if (configManager.getConfig('crowi', 'security:registrationMode') !== aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED) {
+          // send mail asynchronous
+          sendEmailToAllAdmins(userData);
+        }
 
-          return registerSuccessHandler(req, res, userData);
-        });
-      });
-    }
-    else { // method GET of form is not valid
-      debug('session is', req.session);
-      const isRegistering = true;
-      return res.render('login', { isRegistering });
-    }
-  };
-
-  async function sendEmailToAllAdmins(userData) {
-    // send mails to all admin users (derived from crowi) -- 2020.06.18 Yuki Takei
-    const admins = await User.findAdmins();
-
-    const appTitle = appService.getAppTitle();
-
-    const promises = admins.map((admin) => {
-      return mailService.send({
-        to: admin.email,
-        subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
-        template: path.join(crowi.localeDir, 'en_US/admin/userWaitingActivation.txt'),
-        vars: {
-          createdUser: userData,
-          admin,
-          url: appService.getSiteUrl(),
-          appTitle,
-        },
+        return registerSuccessHandler(req, res, userData);
       });
     });
-
-    const results = await Promise.allSettled(promises);
-    results
-      .filter(result => result.status === 'rejected')
-      .forEach(result => logger.error(result.reason));
-  }
+  };
 
   actions.invited = async function(req, res) {
     if (!req.user) {

+ 0 - 1
packages/app/src/server/service/app.ts

@@ -114,7 +114,6 @@ export default class AppService implements S2sMessageHandlable {
   }
 
   async setupAfterInstall(): Promise<void> {
-    await this.crowi.pluginService.autoDetectAndLoadPlugins();
     this.crowi.setupRoutesAtLast();
     this.crowi.setupGlobalErrorHandlers();
   }

+ 2 - 2
packages/app/src/server/service/installer.ts

@@ -109,7 +109,7 @@ export class InstallerService {
     return configManager.updateConfigsInTheSameNamespace('crowi', initialConfig, true);
   }
 
-  async install(firstAdminUserToSave: IUser, globalLang: Lang, options?: AutoInstallOptions): Promise<IUser> {
+  async install(firstAdminUserToSave: Pick<IUser, 'name' | 'username' | 'email' | 'password'>, globalLang: Lang, options?: AutoInstallOptions): Promise<IUser> {
     await this.initDB(globalLang, options);
 
     // TODO typescriptize models/user.js and remove eslint-disable-next-line
@@ -144,7 +144,7 @@ export class InstallerService {
     const rootRevision = await Revision.findOne({ path: '/' });
     rootPage.creator = adminUser._id;
     rootPage.lastUpdateUser = adminUser._id;
-    rootRevision.creator = adminUser._id;
+    rootRevision.author = adminUser._id;
     await Promise.all([rootPage.save(), rootRevision.save()]);
 
     // create initial pages

+ 54 - 0
packages/app/src/services/renderer/rehype-plugins/relocate-toc.ts

@@ -0,0 +1,54 @@
+import rehypeToc, { HtmlElementNode } from 'rehype-toc';
+import { Plugin } from 'unified';
+import { Node } from 'unist';
+
+type StoreTocPluginParams = {
+  storeTocNode: (toc: HtmlElementNode) => void,
+}
+
+export const rehypePluginStore: Plugin<[StoreTocPluginParams]> = (options) => {
+  return rehypeToc.bind(this)({
+    nav: false,
+    headings: ['h1', 'h2', 'h3'],
+    customizeTOC: (toc: HtmlElementNode) => {
+      // For storing tocNode to global state with swr
+      // search: tocRef.current
+      options.storeTocNode(toc);
+
+      return false; // not show toc in body
+    },
+  });
+};
+
+
+// method for replace <ol> to <ul>
+const replaceOlToUl = (children: Node[]) => {
+  children.forEach((child) => {
+    if (child.type === 'element' && child.tagName === 'ol') {
+      child.tagName = 'ul';
+    }
+    if (child.children != null) {
+      replaceOlToUl(child.children as Node[]);
+    }
+  });
+};
+
+type RestoreTocPluginParams = {
+  tocNode?: HtmlElementNode,
+}
+
+export const rehypePluginRestore: Plugin<[RestoreTocPluginParams]> = (options) => {
+  const { tocNode } = options;
+
+  return rehypeToc.bind(this)({
+    headings: ['h1', 'h2', 'h3'],
+    customizeTOC: () => {
+      if (tocNode != null) {
+        replaceOlToUl([tocNode]); // replace <ol> to <ul>
+
+        // restore toc
+        return tocNode;
+      }
+    },
+  });
+};

+ 12 - 0
packages/app/src/services/renderer/remark-plugins/plantuml.ts

@@ -0,0 +1,12 @@
+import plantuml from '@akebifiky/remark-simple-plantuml';
+import { Plugin } from 'unified';
+
+type PlantUMLPluginParams = {
+  baseUrl?: string,
+}
+
+export const remarkPlugin: Plugin<[PlantUMLPluginParams]> = (options) => {
+  const baseUrl = options.baseUrl ?? 'https://www.plantuml.com/plantuml/svg';
+
+  return plantuml.bind(this)({ baseUrl });
+};

+ 9 - 29
packages/app/src/services/renderer/renderer.tsx

@@ -12,7 +12,7 @@ import katex from 'rehype-katex';
 import raw from 'rehype-raw';
 import sanitize, { defaultSchema as sanitizeDefaultSchema } from 'rehype-sanitize';
 import slug from 'rehype-slug';
-import toc, { HtmlElementNode } from 'rehype-toc';
+import { HtmlElementNode } from 'rehype-toc';
 import breaks from 'remark-breaks';
 import emoji from 'remark-emoji';
 import gfm from 'remark-gfm';
@@ -32,6 +32,8 @@ import * as addLineNumberAttribute from './rehype-plugins/add-line-number-attrib
 import * as keywordHighlighter from './rehype-plugins/keyword-highlighter';
 import { relativeLinks } from './rehype-plugins/relative-links';
 import { relativeLinksByPukiwikiLikeLinker } from './rehype-plugins/relative-links-by-pukiwiki-like-linker';
+import * as toc from './rehype-plugins/relocate-toc';
+import * as plantuml from './remark-plugins/plantuml';
 import { pukiwikiLikeLinker } from './remark-plugins/pukiwiki-like-linker';
 import * as xsvToTable from './remark-plugins/xsv-to-table';
 
@@ -247,6 +249,7 @@ export type RendererOptions = Omit<ReactMarkdownOptions, 'remarkPlugins' | 'rehy
 const commonSanitizeOption: SanitizeOption = deepmerge(
   sanitizeDefaultSchema,
   {
+    clobberPrefix: 'mdcont-',
     attributes: {
       '*': ['class', 'className', 'style'],
     },
@@ -316,6 +319,7 @@ export const generateViewOptions = (
   // add remark plugins
   remarkPlugins.push(
     math,
+    [plantuml.remarkPlugin, { baseUrl: config.plantumlUri }],
     xsvToTable.remarkPlugin,
     lsxGrowiPlugin.remarkPlugin,
   );
@@ -326,36 +330,13 @@ export const generateViewOptions = (
   // add rehype plugins
   rehypePlugins.push(
     slug,
-    [toc, {
-      nav: false,
-      headings: ['h1', 'h2', 'h3'],
-      customizeTOC: (toc: HtmlElementNode) => {
-        // method for replace <ol> to <ul>
-        const replacer = (children) => {
-          children.forEach((child) => {
-            if (child.type === 'element' && child.tagName === 'ol') {
-              child.tagName = 'ul';
-            }
-            if (child.children) {
-              replacer(child.children);
-            }
-          });
-        };
-        replacer([toc]); // replace <ol> to <ul>
-
-        // For storing tocNode to global state with swr
-        // search: tocRef.current
-        storeTocNode(toc);
-
-        return false; // not show toc in body
-      },
-    }],
     [lsxGrowiPlugin.rehypePlugin, { pagePath }],
     [sanitize, deepmerge(
       commonSanitizeOption,
       lsxGrowiPlugin.sanitizeOption,
     )],
     katex,
+    [toc.rehypePluginStore, { storeTocNode }],
     // [autoLinkHeadings, {
     //   behavior: 'append',
     // }]
@@ -396,10 +377,7 @@ export const generateTocOptions = (config: RendererConfig, tocNode: HtmlElementN
 
   // add rehype plugins
   rehypePlugins.push(
-    [toc, {
-      headings: ['h1', 'h2', 'h3'],
-      customizeTOC: () => tocNode,
-    }],
+    [toc.rehypePluginRestore, { tocNode }],
     [sanitize, commonSanitizeOption],
   );
   // renderer.rehypePlugins.push([autoLinkHeadings, {
@@ -418,6 +396,7 @@ export const generateSimpleViewOptions = (config: RendererConfig, pagePath: stri
   // add remark plugins
   remarkPlugins.push(
     math,
+    [plantuml.remarkPlugin, { baseUrl: config.plantumlUri }],
     xsvToTable.remarkPlugin,
     lsxGrowiPlugin.remarkPlugin,
   );
@@ -453,6 +432,7 @@ export const generatePreviewOptions = (config: RendererConfig, pagePath: string)
   // add remark plugins
   remarkPlugins.push(
     math,
+    [plantuml.remarkPlugin, { baseUrl: config.plantumlUri }],
     xsvToTable.remarkPlugin,
     lsxGrowiPlugin.remarkPlugin,
   );

+ 13 - 9
packages/app/src/stores/attachment.tsx

@@ -1,11 +1,13 @@
 import { useCallback } from 'react';
 
 import {
+  HasObjectId,
   IAttachment, Nullable, SWRResponseWithUtils, withUtils,
 } from '@growi/core';
 import useSWR from 'swr';
 
-import { apiGet, apiPost } from '~/client/util/apiv1-client';
+import { apiPost } from '~/client/util/apiv1-client';
+import { apiv3Get } from '~/client/util/apiv3-client';
 import { IResAttachmentList } from '~/interfaces/attachment';
 
 type Util = {
@@ -13,7 +15,7 @@ type Util = {
 };
 
 type IDataAttachmentList = {
-  attachments: IAttachment[]
+  attachments: (IAttachment & HasObjectId)[]
   totalAttachments: number
   limit: number
 };
@@ -21,17 +23,19 @@ type IDataAttachmentList = {
 export const useSWRxAttachments = (pageId?: Nullable<string>, pageNumber?: number): SWRResponseWithUtils<Util, IDataAttachmentList, Error> => {
   const shouldFetch = pageId != null && pageNumber != null;
 
-  const fetcher = useCallback(async(endpoint) => {
-    const res = await apiGet<IResAttachmentList>(endpoint, { pageId, pageNumber });
+  const fetcher = useCallback(async(endpoint, pageId, pageNumber) => {
+    const res = await apiv3Get<IResAttachmentList>(endpoint, { pageId, pageNumber });
+    const resAttachmentList = res.data;
+    const { paginateResult } = resAttachmentList;
     return {
-      attachments: res.data.paginateResult.docs,
-      totalAttachments: res.data.paginateResult.totalDocs,
-      limit: res.data.paginateResult.limit,
+      attachments: paginateResult.docs,
+      totalAttachments: paginateResult.totalDocs,
+      limit: paginateResult.limit,
     };
-  }, [pageId, pageNumber]);
+  }, []);
 
   const swrResponse = useSWR(
-    shouldFetch ? ['/attachments/list', pageId, pageNumber] : null,
+    shouldFetch ? ['/attachment/list', pageId, pageNumber] : null,
     fetcher,
   );
 

+ 6 - 7
packages/app/src/stores/ui.tsx

@@ -1,7 +1,7 @@
 import { RefObject } from 'react';
 
 import {
-  isClient, isServer, pagePathUtils, Nullable,
+  isClient, isServer, pagePathUtils, Nullable, PageGrant,
 } from '@growi/core';
 import { withUtils, SWRResponseWithUtils } from '@growi/core/src/utils/with-utils';
 import { Breakpoint, addBreakpointListener } from '@growi/ui';
@@ -27,7 +27,7 @@ import {
 import { localStorageMiddleware } from './middlewares/sync-to-storage';
 import { useStaticSWR } from './use-static-swr';
 
-const { isTrashTopPage } = pagePathUtils;
+const { isTrashTopPage, isUsersTopPage } = pagePathUtils;
 
 const logger = loggerFactory('growi:stores:ui');
 
@@ -367,7 +367,7 @@ export const useSidebarResizeDisabled = (isDisabled?: boolean): SWRResponse<bool
 };
 
 export const useSelectedGrant = (initialData?: Nullable<IPageGrantData>): SWRResponse<Nullable<IPageGrantData>, Error> => {
-  return useStaticSWR<Nullable<IPageGrantData>, Error>('selectedGrant', initialData);
+  return useStaticSWR<Nullable<IPageGrantData>, Error>('selectedGrant', initialData, { fallbackData: { grant: PageGrant.GRANT_PUBLIC } });
 };
 
 export const useGlobalSearchFormRef = (initialData?: RefObject<IFocusable>): SWRResponse<RefObject<IFocusable>, Error> => {
@@ -424,22 +424,21 @@ export const useIsAbleToShowPageManagement = (): SWRResponse<boolean, Error> =>
 export const useIsAbleToShowTagLabel = (): SWRResponse<boolean, Error> => {
   const key = 'isAbleToShowTagLabel';
   const { data: pageId } = useCurrentPageId();
-  const { data: isUserPage } = useIsUserPage();
   const { data: currentPagePath } = useCurrentPagePath();
   const { data: isIdenticalPath } = useIsIdenticalPath();
   const { data: isNotFound } = useIsNotFound();
   const { data: editorMode } = useEditorMode();
   const { data: shareLinkId } = useShareLinkId();
 
-  const includesUndefined = [isUserPage, currentPagePath, isIdenticalPath, isNotFound, editorMode].some(v => v === undefined);
+  const includesUndefined = [currentPagePath, isIdenticalPath, isNotFound, editorMode].some(v => v === undefined);
 
   const isViewMode = editorMode === EditorMode.View;
 
   return useSWRImmutable(
-    includesUndefined ? null : [key, editorMode, pageId],
+    includesUndefined ? null : [key, pageId, currentPagePath, isIdenticalPath, isNotFound, editorMode, shareLinkId],
     // "/trash" page does not exist on page collection and unable to add tags
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    () => !isUserPage && !isTrashTopPage(currentPagePath!) && shareLinkId == null && !isIdenticalPath && !(isViewMode && isNotFound),
+    () => !isUsersTopPage(currentPagePath!) && !isTrashTopPage(currentPagePath!) && shareLinkId == null && !isIdenticalPath && !(isViewMode && isNotFound),
   );
 };
 

+ 0 - 17
packages/app/src/styles/atoms/_buttons.scss

@@ -1,23 +1,6 @@
 @use '../bootstrap/init' as bs;
 @use '../mixins';
 
-.btn.btn-seen-user {
-  $color-seen-user: #549c79;
-
-  @include bs.button-outline-variant($color-seen-user, $color-seen-user, rgba(lighten($color-seen-user, 10%), 0.15), rgba(lighten($color-seen-user, 10%), 0.5));
-  @include mixins.button-outline-svg-icon-variant($color-seen-user, $color-seen-user);
-  &:not(:disabled):not(.disabled):active,
-  &:not(:disabled):not(.disabled).active {
-    color: $color-seen-user;
-    svg {
-      fill: $color-seen-user;
-    }
-  }
-  &:not(:disabled):not(.disabled):not(:hover) {
-    background-color: transparent;
-  }
-}
-
 .btn-copy,
 .btn-edit {
   &:not(:hover):not(:active) {

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

@@ -245,6 +245,15 @@ ul.pagination {
   }
 }
 
+/*
+ * GROWI ToC
+ */
+.revision-toc-content {
+  ::marker {
+    color: lighten($bgcolor-global, 30%);
+  }
+}
+
 /*
  * GROWI subnavigation
  */

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

@@ -242,6 +242,15 @@ $dropdown-link-active-bg: $bgcolor-dropdown-link-active;
   }
 }
 
+/*
+ * GROWI ToC
+ */
+.revision-toc-content {
+  ::marker {
+    color: darken($bgcolor-global, 20%);
+  }
+}
+
 /*
  * GROWI on-edit
  */

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

@@ -169,7 +169,7 @@ ul.pagination {
 
 .grw-navbar {
   background: $bgcolor-navbar;
-  .nav-item > .nav-link {
+  .nav-item .nav-link {
     color: $color-link-nabvar;
   }
 

+ 1 - 0
packages/core/src/interfaces/user.ts

@@ -20,6 +20,7 @@ export type IUser = {
   createdAt: Date,
   lastLoginAt?: Date,
   introduction: string,
+  status: number,
 }
 
 export type IUserGroupRelation = {

+ 3 - 1
packages/ui/src/components/Attachment/Attachment.jsx

@@ -60,7 +60,9 @@ export class Attachment extends React.Component {
         <span className="mr-1 attachment-userpicture">
           <UserPicture user={attachment.creator} size="sm"></UserPicture>
         </span>
-        <a className="mr-2" href={attachment.filePathProxied}><i className={formatIcon}></i> {attachment.originalName}</a>
+        <a className="mr-2" href={attachment.filePathProxied} target="_blank" rel="noopener noreferrer">
+          <i className={formatIcon}></i> {attachment.originalName}
+        </a>
         <span className="mr-2">{fileType}</span>
         <span className="mr-2">{fileInUse}</span>
         <span className="mr-2">{btnDownload}</span>

+ 57 - 31
yarn.lock

@@ -2,6 +2,14 @@
 # yarn lockfile v1
 
 
+"@akebifiky/remark-simple-plantuml@^1.0.2":
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/@akebifiky/remark-simple-plantuml/-/remark-simple-plantuml-1.0.2.tgz#c353e4be4e5338b0165f1d6060da4960c325bad5"
+  integrity sha512-y5rWgQvU+DMpLKx1KlXCsgUeqVooqQm1S3hePLF9iecZy6YhKRybznFdvAvoAoiV2GoGhObQDHnneAl93llIcg==
+  dependencies:
+    plantuml-encoder "^1.4.0"
+    unist-util-visit "^2.0.2"
+
 "@alienfast/i18next-loader@^1.1.4":
   version "1.1.4"
   resolved "https://registry.yarnpkg.com/@alienfast/i18next-loader/-/i18next-loader-1.1.4.tgz#213a6cd77222900a61b1635a212051193bcd5d1f"
@@ -1433,13 +1441,6 @@
   dependencies:
     regenerator-runtime "^0.13.4"
 
-"@babel/runtime@^7.13.17", "@babel/runtime@^7.14.0", "@babel/runtime@^7.14.5", "@babel/runtime@^7.17.2":
-  version "7.18.6"
-  resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.18.6.tgz#6a1ef59f838debd670421f8c7f2cbb8da9751580"
-  integrity sha512-t9wi7/AW6XtKahAe20Yw0/mMljKq0B1r2fPdvaAdV/KPDZewFXdaaa6K7lxmZBZ8FBNpCiAT6iHPmd6QO9bKfQ==
-  dependencies:
-    regenerator-runtime "^0.13.4"
-
 "@babel/runtime@^7.13.8", "@babel/runtime@^7.8.7":
   version "7.17.7"
   resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.17.7.tgz#a5f3328dc41ff39d803f311cfe17703418cf9825"
@@ -1447,6 +1448,13 @@
   dependencies:
     regenerator-runtime "^0.13.4"
 
+"@babel/runtime@^7.14.0", "@babel/runtime@^7.14.5", "@babel/runtime@^7.17.2":
+  version "7.18.6"
+  resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.18.6.tgz#6a1ef59f838debd670421f8c7f2cbb8da9751580"
+  integrity sha512-t9wi7/AW6XtKahAe20Yw0/mMljKq0B1r2fPdvaAdV/KPDZewFXdaaa6K7lxmZBZ8FBNpCiAT6iHPmd6QO9bKfQ==
+  dependencies:
+    regenerator-runtime "^0.13.4"
+
 "@babel/runtime@^7.14.6", "@babel/runtime@^7.15.4", "@babel/runtime@^7.9.2":
   version "7.16.7"
   resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.16.7.tgz#03ff99f64106588c9c403c6ecb8c3bafbbdff1fa"
@@ -1454,6 +1462,13 @@
   dependencies:
     regenerator-runtime "^0.13.4"
 
+"@babel/runtime@^7.18.6":
+  version "7.19.0"
+  resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.19.0.tgz#22b11c037b094d27a8a2504ea4dcff00f50e2259"
+  integrity sha512-eR8Lo9hnDS7tqkO7NsV+mKvCmv5boaXFSZ70DnfhcgiEne8hv9oCEd36Klw74EtizEqLsy4YnW8UWwpBVolHZA==
+  dependencies:
+    regenerator-runtime "^0.13.4"
+
 "@babel/runtime@^7.6.3":
   version "7.7.7"
   resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.7.7.tgz#194769ca8d6d7790ec23605af9ee3e42a0aa79cf"
@@ -11574,7 +11589,7 @@ hogan.js@3.0.2:
     mkdirp "0.3.0"
     nopt "1.0.10"
 
-hoist-non-react-statics@^3.2.0, hoist-non-react-statics@^3.3.0, hoist-non-react-statics@^3.3.2:
+hoist-non-react-statics@^3.3.0, hoist-non-react-statics@^3.3.2:
   version "3.3.2"
   resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45"
   integrity sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==
@@ -11609,11 +11624,6 @@ html-escaper@^2.0.0:
   resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.0.tgz#71e87f931de3fe09e56661ab9a29aadec707b491"
   integrity sha512-a4u9BeERWGu/S8JiWEAQcdrg9v4QArtP9keViQjGMdff20fBdd8waotXaNmODqBe6uZ3Nafi7K/ho4gCQHV3Ig==
 
-html-escaper@^2.0.2:
-  version "2.0.2"
-  resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453"
-  integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==
-
 html-parse-stringify@^3.0.1:
   version "3.0.1"
   resolved "https://registry.yarnpkg.com/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz#dfc1017347ce9f77c8141a507f233040c59c55d2"
@@ -11799,10 +11809,10 @@ i18next-localstorage-backend@^3.1.3:
   dependencies:
     "@babel/runtime" "^7.14.6"
 
-i18next@^21.6.14:
-  version "21.8.11"
-  resolved "https://registry.yarnpkg.com/i18next/-/i18next-21.8.11.tgz#197aac04be51b7083999a2cb63deb831cf1ba4c8"
-  integrity sha512-+s8N6kQShwNK+Ua/+VsS/Sji24NUJJLBk9QIucygj1f97f4hPNDWmLP9fQCI4d5+XLfXJ3JctX4g+zJla967Vw==
+i18next@^21.8.13:
+  version "21.9.2"
+  resolved "https://registry.yarnpkg.com/i18next/-/i18next-21.9.2.tgz#3f7c5594393eb27117c1db4c38f5ec766e68de0e"
+  integrity sha512-00fVrLQOwy45nm3OtC9l1WiLK3nJlIYSljgCt0qzTaAy65aciMdRy9GsuW+a2AtKtdg9/njUGfRH30LRupV7ZQ==
   dependencies:
     "@babel/runtime" "^7.17.2"
 
@@ -16100,18 +16110,18 @@ nested-error-stacks@^2.0.0:
   resolved "https://registry.yarnpkg.com/nested-error-stacks/-/nested-error-stacks-2.1.0.tgz#0fbdcf3e13fe4994781280524f8b96b0cdff9c61"
   integrity sha512-AO81vsIO1k1sM4Zrd6Hu7regmJN1NSiAja10gc4bX3F0wd+9rQmcuHQaHVQCYIEC8iFXnE+mavh23GOt7wBgug==
 
-next-i18next@^11.0.0:
-  version "11.0.0"
-  resolved "https://registry.yarnpkg.com/next-i18next/-/next-i18next-11.0.0.tgz#2857d13c58a5ed976fe57c44286f1520b07f7c96"
-  integrity sha512-phxbQiZGSJTTBE2FI4+BnqFZl88AI2V+6MrEQnT9aPFAXq/fATQ/F0pOUM3J7kU4nEeCfn3hjISq+ygGHlEz0g==
+next-i18next@^11.3.0:
+  version "11.3.0"
+  resolved "https://registry.yarnpkg.com/next-i18next/-/next-i18next-11.3.0.tgz#bfce51d8df07fb5cd61097423eeb7d744e09ae25"
+  integrity sha512-xl0oIRtiVrk9ZaWBRUbNk/prva4Htdu59o9rFWzd9ax/KemaDVuTTuBZTQMkmXohUQk/MJ7w1rV/mICL6TzyGw==
   dependencies:
-    "@babel/runtime" "^7.13.17"
+    "@babel/runtime" "^7.18.6"
     "@types/hoist-non-react-statics" "^3.3.1"
     core-js "^3"
-    hoist-non-react-statics "^3.2.0"
-    i18next "^21.6.14"
+    hoist-non-react-statics "^3.3.2"
+    i18next "^21.8.13"
     i18next-fs-backend "^1.1.4"
-    react-i18next "^11.16.2"
+    react-i18next "^11.18.0"
 
 next-superjson@^0.0.4:
   version "0.0.4"
@@ -17726,7 +17736,7 @@ pkg-dir@^5.0.0:
   dependencies:
     find-up "^5.0.0"
 
-plantuml-encoder@^1.2.5:
+plantuml-encoder@^1.2.5, plantuml-encoder@^1.4.0:
   version "1.4.0"
   resolved "https://registry.yarnpkg.com/plantuml-encoder/-/plantuml-encoder-1.4.0.tgz#7899302cf785de956bf1a167e15420feee5975f7"
   integrity sha512-sxMwpDw/ySY1WB2CE3+IdMuEcWibJ72DDOsXLkSmEaSzwEUaYBT6DWgOfBiHGCux4q433X6+OEFWjlVqp7gL6g==
@@ -18442,13 +18452,12 @@ react-hotkeys@^2.0.0:
   dependencies:
     prop-types "^15.6.1"
 
-react-i18next@^11.16.2:
-  version "11.17.3"
-  resolved "https://registry.yarnpkg.com/react-i18next/-/react-i18next-11.17.3.tgz#eff742f162f1a413056fb510e8b830d42c8c020d"
-  integrity sha512-rIrLl5cLDoHdXFWdjKurRpatA3MPC9j3yTZidv0GmJEea5+XGXl42p7NupA1dmghoLGOXllShNUobgPYtgEcRA==
+react-i18next@^11.18.0:
+  version "11.18.6"
+  resolved "https://registry.yarnpkg.com/react-i18next/-/react-i18next-11.18.6.tgz#e159c2960c718c1314f1e8fcaa282d1c8b167887"
+  integrity sha512-yHb2F9BiT0lqoQDt8loZ5gWP331GwctHz9tYQ8A2EIEUu+CcEdjBLQWli1USG3RdWQt3W+jqQLg/d4rrQR96LA==
   dependencies:
     "@babel/runtime" "^7.14.5"
-    html-escaper "^2.0.2"
     html-parse-stringify "^3.0.1"
 
 react-image-crop@^8.3.0:
@@ -18586,6 +18595,14 @@ react-popper@^2.2.5:
     react-fast-compare "^3.0.1"
     warning "^4.0.2"
 
+react-scroll@^1.8.7:
+  version "1.8.7"
+  resolved "https://registry.yarnpkg.com/react-scroll/-/react-scroll-1.8.7.tgz#8020035329efad00f03964e18aff6822137de3aa"
+  integrity sha512-fBOIwweAlhicx8RqP9tQXn/Uhd+DTtVRjw+0VBsIn1Z+MjRYLhTZ0tMoTAU1vOD3dce8mI6copexI4yWII+Luw==
+  dependencies:
+    lodash.throttle "^4.1.1"
+    prop-types "^15.7.2"
+
 react-scrolllock@^1.0.9:
   version "1.0.9"
   resolved "https://registry.yarnpkg.com/react-scrolllock/-/react-scrolllock-1.0.9.tgz#7c9c3c0cce2ed55042af2808b6483b85b121cdcb"
@@ -23860,6 +23877,15 @@ unist-util-visit@^1.1.0:
   dependencies:
     unist-util-visit-parents "^2.0.0"
 
+unist-util-visit@^2.0.2:
+  version "2.0.3"
+  resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-2.0.3.tgz#c3703893146df47203bb8a9795af47d7b971208c"
+  integrity sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q==
+  dependencies:
+    "@types/unist" "^2.0.0"
+    unist-util-is "^4.0.0"
+    unist-util-visit-parents "^3.0.0"
+
 unist-util-visit@^3.0.0:
   version "3.1.0"
   resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-3.1.0.tgz#9420d285e1aee938c7d9acbafc8e160186dbaf7b"