Explorar o código

Merge branch 'master' into support/use-jotai

Yuki Takei hai 5 meses
pai
achega
6fec300438
Modificáronse 77 ficheiros con 4160 adicións e 3329 borrados
  1. 398 0
      .serena/memories/apps-app-admin-forms-react-hook-form-migration-guide.md
  2. 28 1
      CHANGELOG.md
  3. 1 0
      apps/app/.eslintrc.js
  4. 1 1
      apps/app/package.json
  5. 50 29
      apps/app/src/client/components/Admin/App/AppSetting.jsx
  6. 7 19
      apps/app/src/client/components/Admin/App/AwsSetting.tsx
  7. 10 20
      apps/app/src/client/components/Admin/App/AzureSetting.tsx
  8. 53 6
      apps/app/src/client/components/Admin/App/FileUploadSetting.tsx
  9. 5 12
      apps/app/src/client/components/Admin/App/GcsSetting.tsx
  10. 56 17
      apps/app/src/client/components/Admin/App/MailSetting.tsx
  11. 19 7
      apps/app/src/client/components/Admin/App/MaskedInput.tsx
  12. 14 14
      apps/app/src/client/components/Admin/App/SesSetting.tsx
  13. 22 9
      apps/app/src/client/components/Admin/App/SiteUrlSetting.tsx
  14. 12 11
      apps/app/src/client/components/Admin/App/SmtpSetting.tsx
  15. 11 2
      apps/app/src/client/components/Admin/Common/AdminUpdateButtonRow.tsx
  16. 29 13
      apps/app/src/client/components/Admin/Customize/CustomizeCssSetting.tsx
  17. 47 31
      apps/app/src/client/components/Admin/Customize/CustomizeNoscriptSetting.tsx
  18. 47 31
      apps/app/src/client/components/Admin/Customize/CustomizeScriptSetting.tsx
  19. 28 15
      apps/app/src/client/components/Admin/Customize/CustomizeTitle.tsx
  20. 208 204
      apps/app/src/client/components/Admin/ImportData/ImportDataPageContents.jsx
  21. 25 28
      apps/app/src/client/components/Admin/LegacySlackIntegration/SlackConfiguration.jsx
  22. 17 26
      apps/app/src/client/components/Admin/MarkdownSetting/WhitelistInput.tsx
  23. 36 30
      apps/app/src/client/components/Admin/MarkdownSetting/XssForm.jsx
  24. 39 46
      apps/app/src/client/components/Admin/Security/GitHubSecuritySettingContents.jsx
  25. 34 48
      apps/app/src/client/components/Admin/Security/GoogleSecuritySettingContents.jsx
  26. 0 450
      apps/app/src/client/components/Admin/Security/LdapSecuritySettingContents.jsx
  27. 446 0
      apps/app/src/client/components/Admin/Security/LdapSecuritySettingContents.tsx
  28. 0 261
      apps/app/src/client/components/Admin/Security/LocalSecuritySettingContents.jsx
  29. 249 0
      apps/app/src/client/components/Admin/Security/LocalSecuritySettingContents.tsx
  30. 0 488
      apps/app/src/client/components/Admin/Security/OidcSecuritySettingContents.jsx
  31. 488 0
      apps/app/src/client/components/Admin/Security/OidcSecuritySettingContents.tsx
  32. 0 563
      apps/app/src/client/components/Admin/Security/SamlSecuritySettingContents.jsx
  33. 549 0
      apps/app/src/client/components/Admin/Security/SamlSecuritySettingContents.tsx
  34. 1 1
      apps/app/src/client/components/Admin/Security/SecurityManagementContents.jsx
  35. 0 635
      apps/app/src/client/components/Admin/Security/SecuritySetting.jsx
  36. 58 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/CommentManageRightsSettings.tsx
  37. 75 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/PageAccessRightsSettings.tsx
  38. 289 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/PageDeleteRightsSettings.tsx
  39. 117 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/PageListDisplaySettings.tsx
  40. 36 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/SessionMaxAgeSettings.tsx
  41. 50 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/UserHomepageDeletionSettings.tsx
  42. 88 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/index.tsx
  43. 65 0
      apps/app/src/client/components/Admin/Security/SecuritySetting/types.ts
  44. 3 2
      apps/app/src/client/services/AdminLdapSecurityContainer.js
  45. 3 3
      apps/app/src/client/services/renderer/renderer.tsx
  46. 9 0
      apps/app/src/features/openai/client/components/AiAssistant/AiAssistantSidebar/AiAssistantSidebar.module.scss
  47. 38 34
      apps/app/src/features/openai/client/components/AiAssistant/AiAssistantSidebar/AiAssistantSidebar.tsx
  48. 32 4
      apps/app/src/features/openai/client/services/knowledge-assistant.tsx
  49. 3 3
      apps/app/src/services/general-xss-filter/general-xss-filter.spec.ts
  50. 4 5
      apps/app/src/services/general-xss-filter/general-xss-filter.ts
  51. 6 2
      apps/app/src/services/layout/use-should-expand-content.ts
  52. 6 5
      apps/app/src/services/renderer/markdown-it/PreProcessor/EasyGrid.js
  53. 13 6
      apps/app/src/services/renderer/recommended-whitelist.spec.ts
  54. 31 20
      apps/app/src/services/renderer/recommended-whitelist.ts
  55. 6 3
      apps/app/src/services/renderer/rehype-plugins/add-class.ts
  56. 4 1
      apps/app/src/services/renderer/rehype-plugins/add-inline-code-property.ts
  57. 4 2
      apps/app/src/services/renderer/rehype-plugins/add-line-number-attribute.ts
  58. 21 11
      apps/app/src/services/renderer/rehype-plugins/keyword-highlighter.ts
  59. 45 39
      apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.spec.ts
  60. 6 2
      apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.ts
  61. 31 33
      apps/app/src/services/renderer/rehype-plugins/relative-links.spec.ts
  62. 14 8
      apps/app/src/services/renderer/rehype-plugins/relative-links.ts
  63. 8 7
      apps/app/src/services/renderer/rehype-plugins/relocate-toc.ts
  64. 10 6
      apps/app/src/services/renderer/remark-plugins/attachment.ts
  65. 4 2
      apps/app/src/services/renderer/remark-plugins/codeblock.ts
  66. 11 6
      apps/app/src/services/renderer/remark-plugins/echo-directive.ts
  67. 2 3
      apps/app/src/services/renderer/remark-plugins/emoji.ts
  68. 13 16
      apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.spec.ts
  69. 34 26
      apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.ts
  70. 6 8
      apps/app/src/services/renderer/remark-plugins/xsv-to-table.ts
  71. 53 39
      apps/app/src/services/renderer/renderer.tsx
  72. 1 1
      apps/slackbot-proxy/package.json
  73. 4 1
      biome.json
  74. 1 1
      package.json
  75. 4 2
      packages/remark-drawio/src/components/DrawioViewer.tsx
  76. 15 8
      packages/remark-drawio/src/services/renderer/remark-drawio.ts
  77. 7 2
      packages/remark-drawio/src/utils/embed.ts

+ 398 - 0
.serena/memories/apps-app-admin-forms-react-hook-form-migration-guide.md

@@ -0,0 +1,398 @@
+# Admin フォーム - React Hook Form 移行ガイドライン
+
+## プロジェクトコンテキスト
+
+### 現状 (2025年10月時点)
+**✅ PR #10051 完了: Admin フォームの IME 問題は100%解決済み**
+
+全27ファイルが React Hook Form に移行完了し、以下の問題を解決:
+1. ✅ **日本語 IME 入力の問題**: 非制御コンポーネント化により完全解決
+2. ✅ **空値更新の問題**: 完全解決
+3. ⏳ **レガシーライブラリ問題**: Unstated は現在も使用中(次のステップで解決予定)
+
+### 最終目標 (理想像)
+- React Hook Form を利用(✅ 完了)
+- Unstated を完全に廃止(⏳ 次のステップ)
+- グローバルステートは Jotai で管理(⏳ 次のステップ)
+
+### 現在の構成 (中間地点)
+**React Hook Form + Unstated Container のハイブリッド構成**
+
+この構成により:
+1. ✅ IME 入力問題を解決(非制御コンポーネント化)
+2. ✅ 空値更新問題を解決
+3. ✅ Container は残しているが、将来的に Jotai への移行パスを確保
+4. ✅ 段階的な移行によりリグレッションを最小化
+
+## 移行パターン(確立済み)
+
+### 基本的なフォームセットアップ
+
+```typescript
+import { useForm } from 'react-hook-form';
+
+type FormData = {
+  fieldName: string;
+  // ... 他のフィールド
+};
+
+const {
+  register,
+  handleSubmit,
+  reset,
+} = useForm<FormData>();
+```
+
+**重要**: `defaultValues` は指定しない。`useEffect` で `reset()` を呼ぶため不要。
+
+### フォーム値の復元
+
+Container の state とフォームを同期するため、`useEffect` で `reset()` を使用:
+
+```typescript
+useEffect(() => {
+  reset({
+    fieldName: container.state.fieldName || '',
+    // ... 他のフィールド
+  });
+}, [container.state.fieldName, reset]);
+```
+
+### Container を使ったフォーム送信
+
+```typescript
+const onSubmit = useCallback(async(data: FormData) => {
+  try {
+    // 重要: API 呼び出し前に setState の完了を待つ
+    await Promise.all([
+      container.changeField1(data.field1),
+      container.changeField2(data.field2),
+    ]);
+    
+    await container.updateHandler();
+    toastSuccess(t('updated_successfully'));
+  }
+  catch (err) {
+    toastError(err);
+  }
+}, [container, t]);
+
+return (
+  <form onSubmit={handleSubmit(onSubmit)}>
+    {/* フォームフィールド */}
+  </form>
+);
+```
+
+## 重要な注意点
+
+### ⚠️ 1. API 呼び出し前に Container の setState を await する(最重要!)
+
+**問題**: Unstated Container の `setState` は非同期処理です。`change*()` メソッドの後に `await` せずに API ハンドラーを即座に呼ぶと、API リクエストは**古い/古びた値**で送信されます。
+
+❌ **間違い:**
+```typescript
+container.changeSiteUrl(data.siteUrl);
+await container.updateHandler(); // 古い値が送信される!
+```
+
+✅ **正しい:**
+```typescript
+await container.changeSiteUrl(data.siteUrl);
+await container.updateHandler(); // 新しい値が送信される
+```
+
+複数フィールドの場合は `Promise.all()` を使用:
+```typescript
+await Promise.all([
+  container.changeTitle(data.title),
+  container.changeConfidential(data.confidential),
+]);
+await container.updateHandler();
+```
+
+### 2. ラジオボタンの値の型の一致
+
+**問題**: ラジオボタンは**文字列**の値を持ちますが、Container の state は boolean かもしれません。型が一致しないと、選択状態の復元ができません。
+
+❌ **間違い:**
+```typescript
+// HTML: <input type="radio" value="true" />
+reset({
+  isEmailPublished: true, // boolean - 文字列 "true" とマッチしない
+});
+```
+
+✅ **正しい:**
+```typescript
+reset({
+  isEmailPublished: String(container.state.isEmailPublished ?? true),
+});
+```
+
+### 3. チェックボックスの値の扱い
+
+チェックボックスは boolean 値を直接使えます(変換不要):
+```typescript
+reset({
+  fileUpload: container.state.fileUpload ?? false,
+});
+```
+
+### 4. リアルタイム Container 更新に watch() を使わない
+
+**削除したパターン**: フォームの変更を `watch()` と `useEffect` でリアルタイムに Container に同期し戻すのは不要で、複雑さを増すだけです。
+
+❌ **これはやらない:**
+```typescript
+const watchedValues = watch();
+useEffect(() => {
+  container.changeField(watchedValues.field);
+}, [watchedValues]);
+```
+
+✅ **submit 時だけ更新:**
+- Container の state は最終的な API リクエストにのみ使用される
+- `onSubmit` で API ハンドラーを呼ぶ前に更新すればよい
+
+### 5. フォームフィールドの disabled vs readOnly
+
+**問題**: `disabled` フィールドはフォーム送信データから除外されます。
+
+フィールドを編集不可にしたいが、フォームデータには含めたい場合:
+- `disabled` の代わりに `readOnly` を使用
+- または属性を削除して Container/API レイヤーで処理
+
+### 6. defaultValues を指定しない
+
+`useForm()` の引数に `defaultValues` を渡さないこと。
+
+理由:
+- `useEffect` で `reset()` を呼んでいるため、初期値はそちらで設定される
+- コードの重複を避ける
+- 他のファイルとパターンを統一
+
+```typescript
+// ❌ 冗長
+const { register, reset } = useForm({
+  defaultValues: { field: container.state.field }
+});
+useEffect(() => {
+  reset({ field: container.state.field });
+}, [container.state.field]);
+
+// ✅ シンプル
+const { register, reset } = useForm();
+useEffect(() => {
+  reset({ field: container.state.field });
+}, [container.state.field]);
+```
+
+## 高度なパターン
+
+### モジュラーコンポーネント設計(SecuritySetting の例)
+
+大規模なフォームは、複数の小さなコンポーネントに分割することを推奨します。
+
+**親コンポーネント(統合):**
+```typescript
+type FormData = {
+  sessionMaxAge: string;
+  // Container で管理される他のフィールドは不要
+};
+
+const Parent: React.FC<Props> = ({ container }) => {
+  const { register, handleSubmit, reset } = useForm<FormData>();
+
+  useEffect(() => {
+    reset({
+      sessionMaxAge: container.state.sessionMaxAge || '',
+    });
+  }, [reset, container.state.sessionMaxAge]);
+
+  const onSubmit = useCallback(async(data: FormData) => {
+    try {
+      // React Hook Form で管理されているフィールドのみ更新
+      await container.setSessionMaxAge(data.sessionMaxAge);
+      // 全ての設定を保存(Container 管理のフィールドも含む)
+      await container.updateGeneralSecuritySetting();
+      toastSuccess(t('updated'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [container, t]);
+
+  return (
+    <form onSubmit={handleSubmit(onSubmit)}>
+      {/* React Hook Form 管理のフィールド */}
+      <SessionMaxAgeSettings register={register} t={t} />
+      
+      {/* Container 直接管理のフィールド */}
+      <PageListDisplaySettings container={container} t={t} />
+      <PageAccessRightsSettings container={container} t={t} />
+      
+      <button type="submit">{t('Update')}</button>
+    </form>
+  );
+};
+```
+
+**子コンポーネント(React Hook Form 管理):**
+```typescript
+type Props = {
+  register: UseFormRegister<{ sessionMaxAge: string }>;
+  t: (key: string) => string;
+};
+
+export const SessionMaxAgeSettings: React.FC<Props> = ({ register, t }) => {
+  return (
+    <input
+      className="form-control"
+      type="text"
+      {...register('sessionMaxAge')}
+      placeholder="2592000000"
+    />
+  );
+};
+```
+
+**子コンポーネント(Container 直接管理):**
+```typescript
+type Props = {
+  container: AdminGeneralSecurityContainer;
+  t: (key: string) => string;
+};
+
+export const PageListDisplaySettings: React.FC<Props> = ({ container, t }) => {
+  return (
+    <select
+      className="form-control"
+      value={container.state.currentOwnerRestrictionDisplayMode}
+      onChange={(e) => container.changeOwnerRestrictionDisplayMode(e.target.value)}
+    >
+      <option value="Displayed">{t('Displayed')}</option>
+      <option value="Hidden">{t('Hidden')}</option>
+    </select>
+  );
+};
+```
+
+### 統一された Submit ボタン
+
+複数のセクションを持つフォームでも、Submit ボタンは1つに統一:
+- React Hook Form のフィールドは `onSubmit` で処理
+- Container 管理のフィールドは既に state に反映されている
+- 1つの `updateHandler()` で全て保存
+
+## テストチェックリスト
+
+フォーム移行後に必ずテストすること:
+
+1. ✅ **日本語 IME 入力と漢字変換** - 最も重要!
+2. ✅ **ページリロード後にフォームの値が正しく復元される**
+3. ✅ **空値を送信できる**(フィールドをクリアできる)
+4. ✅ **フォーム送信で現在の入力値が送信される**(古い/古びた値ではない)
+5. ✅ **ラジオボタンとチェックボックスが正しく復元される**
+6. ✅ **複数セクションがある場合、全ての設定が1つの Submit で保存される**
+
+## PR #10051 の成果
+
+全27ファイルを React Hook Form に移行完了:
+
+### 主要な成果
+1. **企業認証システム**: LDAP (10フィールド)、OIDC (16フィールド)、SAML (9フィールド)
+2. **SecuritySetting のモジュラー化**: 636行のクラスコンポーネント → 8つの Function Component
+3. **セキュリティ設定**: LocalSecurity (1フィールド)、Import (4フィールド)
+4. **カスタマイズ**: CustomizeCss (1フィールド)、Slack (2フィールド)
+5. **その他**: 17ファイル
+
+### アーキテクチャの改善
+- TypeScript 完全対応
+- PropTypes 廃止
+- Function Component への統一
+- モジュラー設計の採用
+- テスト容易性の向上
+
+## 将来の移行パス: Unstated から Jotai へ
+
+### フェーズ 1: React Hook Form 移行(✅ 完了)
+- 全ての Admin フォームを React Hook Form に移行
+- IME 問題と空値問題を解決
+- 非制御コンポーネントパターンを確立
+
+### フェーズ 2: Jotai 導入準備(次のステップ)
+1. **Container の分析**
+   - どの state が本当にグローバルである必要があるか特定
+   - ローカル state で十分なものを useState に移行
+
+2. **API レイヤーの分離**
+   - Container の `update*Handler()` メソッドを独立した API 関数に抽出
+   - `apps/app/src/client/util/apiv3-client.ts` パターンに従う
+
+3. **段階的な Container の削除**
+   - 小さな Container から始める
+   - Jotai atom で置き換え
+   - 各ステップでテストを実行
+
+### フェーズ 3: 完全な Jotai 移行(最終目標)
+```typescript
+// 理想的な最終形態
+import { atom, useAtom } from 'jotai';
+import { useForm } from 'react-hook-form';
+
+// グローバル state
+const sessionMaxAgeAtom = atom<string>('');
+
+const SecuritySetting = () => {
+  const [sessionMaxAge, setSessionMaxAge] = useAtom(sessionMaxAgeAtom);
+  const { register, handleSubmit, reset } = useForm();
+
+  useEffect(() => {
+    reset({ sessionMaxAge });
+  }, [sessionMaxAge, reset]);
+
+  const onSubmit = async(data: FormData) => {
+    // 直接 API 呼び出し
+    await apiv3Put('/admin/security-settings', {
+      sessionMaxAge: data.sessionMaxAge,
+      // ... 他の設定
+    });
+    
+    // Jotai state を更新
+    setSessionMaxAge(data.sessionMaxAge);
+    toastSuccess('Updated');
+  };
+
+  return <form onSubmit={handleSubmit(onSubmit)}>{/* ... */}</form>;
+};
+```
+
+## 適用可能な範囲
+
+このガイドラインは以下の Admin フォームに適用可能:
+
+- Unstated Container でグローバルステートを管理しているフォーム
+- `apps/app/src/client/services/Admin*Container.js` 配下の Container を使用しているフォーム
+- `/admin` ルート配下のコンポーネント
+- 将来的に Jotai に移行予定のフォーム
+
+## 関連ファイル
+
+### 現在使用中
+- Container 群: `apps/app/src/client/services/Admin*Container.js`
+- ボタンコンポーネント: `apps/app/src/client/components/Admin/Common/AdminUpdateButtonRow.tsx`
+- React Hook Form: v7.45.4
+
+### 将来導入予定
+- Jotai: グローバル state 管理
+- SWR または React Query: サーバー state 管理(検討中)
+
+## 参考実装
+
+以下のファイルがベストプラクティスの参考になります:
+
+1. **モジュラー構造**: `apps/app/src/client/components/Admin/Security/SecuritySetting/`
+2. **React Hook Form 基本**: `apps/app/src/client/components/Admin/Security/OidcSecuritySettingContents.tsx`
+3. **複雑なフォーム**: `apps/app/src/client/components/Admin/Security/SamlSecuritySettingContents.tsx`
+4. **既存の良い実装**: `apps/app/src/client/components/Admin/Customize/CustomizeCssSetting.tsx`

+ 28 - 1
CHANGELOG.md

@@ -1,9 +1,36 @@
 # Changelog
 
-## [Unreleased](https://github.com/growilabs/compare/v7.3.2...HEAD)
+## [Unreleased](https://github.com/growilabs/compare/v7.3.3...HEAD)
 
 *Please do not manually update this file. We've automated the process.*
 
+## [v7.3.3](https://github.com/growilabs/compare/v7.3.2...v7.3.3) - 2025-10-15
+
+### 💎 Features
+
+* feat(otel): Page counts metrics (#10367) @Ryosei-Fukushima
+
+### 🚀 Improvement
+
+* imprv: Improve KnowledgeAssistant chat UI UX (#10355) @satof3
+* imprv: Guest user client performance by Socket.io event optimization (#10379) @yuki-takei
+* imprv: PageTree performance by page-listing API (#10362) @yuki-takei
+
+### 🐛 Bug Fixes
+
+* fix: Draw.io color mode (#10390) @miya
+* fix: Cannot update v4 format pages (#10378) @miya
+* fix: Bulk export cleanup and notification occasionally not working on job expire (#10366) @arafubeatbox
+
+### 🧰 Maintenance
+
+* support: Configure biome for app services dir (#10381) @arafubeatbox
+* support: Configure biome for app etc. dirs (#10380) @arafubeatbox
+* support: Configure biome for rate-limiter feature (#10376) @arafubeatbox
+* support: Configure biome for growi-plugin feature (#10309) @arafubeatbox
+* support: Service integration test biome migration (#10234) @arafubeatbox
+* support: Update axios (#10353) @arafubeatbox
+
 ## [v7.3.2](https://github.com/growilabs/compare/v7.3.1...v7.3.2) - 2025-09-29
 
 ### 🚀 Improvement

+ 1 - 0
apps/app/.eslintrc.js

@@ -50,6 +50,7 @@ module.exports = {
     'src/stores-universal/**',
     'src/interfaces/**',
     'src/utils/**',
+    'src/services/**',
     'src/states/**',
   ],
   settings: {

+ 1 - 1
apps/app/package.json

@@ -1,6 +1,6 @@
 {
   "name": "@growi/app",
-  "version": "7.3.3-RC.0",
+  "version": "7.3.4-RC.0",
   "license": "MIT",
   "private": "true",
   "scripts": {

+ 50 - 29
apps/app/src/client/components/Admin/App/AppSetting.jsx

@@ -1,7 +1,8 @@
-import React, { useCallback } from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation, i18n } from 'next-i18next';
 import PropTypes from 'prop-types';
+import { useForm } from 'react-hook-form';
 
 import { i18n as i18nConfig } from '^/config/next-i18next.config';
 
@@ -20,8 +21,44 @@ const AppSetting = (props) => {
   const { adminAppContainer } = props;
   const { t } = useTranslation(['admin', 'commons']);
 
-  const submitHandler = useCallback(async() => {
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
+
+  // Reset form when adminAppContainer state changes (e.g., after reload)
+  useEffect(() => {
+    reset({
+      title: adminAppContainer.state.title || '',
+      confidential: adminAppContainer.state.confidential || '',
+      globalLang: adminAppContainer.state.globalLang || 'en-US',
+      // Convert boolean to string for radio button value
+      isEmailPublishedForNewUser: String(adminAppContainer.state.isEmailPublishedForNewUser ?? true),
+      fileUpload: adminAppContainer.state.fileUpload ?? false,
+    });
+  }, [
+    adminAppContainer.state.title,
+    adminAppContainer.state.confidential,
+    adminAppContainer.state.globalLang,
+    adminAppContainer.state.isEmailPublishedForNewUser,
+    adminAppContainer.state.fileUpload,
+    reset,
+  ]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
+      // Await all setState completions before API call
+      await Promise.all([
+        adminAppContainer.changeTitle(data.title),
+        adminAppContainer.changeConfidential(data.confidential),
+        adminAppContainer.changeGlobalLang(data.globalLang),
+      ]);
+      // Convert string 'true'/'false' to boolean
+      const isEmailPublished = data.isEmailPublishedForNewUser === 'true' || data.isEmailPublishedForNewUser === true;
+      await adminAppContainer.changeIsEmailPublishedForNewUserShow(isEmailPublished);
+      await adminAppContainer.changeFileUpload(data.fileUpload);
+
       await adminAppContainer.updateAppSettingHandler();
       toastSuccess(t('commons:toaster.update_successed', { target: t('commons:headers.app_settings') }));
     }
@@ -33,18 +70,15 @@ const AppSetting = (props) => {
 
 
   return (
-    <React.Fragment>
+    <form onSubmit={handleSubmit(onSubmit)}>
       <div className="row">
         <label className="text-start text-md-end col-md-3 col-form-label">{t('admin:app_setting.site_name')}</label>
         <div className="col-md-6">
           <input
             className="form-control"
             type="text"
-            value={adminAppContainer.state.title || ''}
-            onChange={(e) => {
-              adminAppContainer.changeTitle(e.target.value);
-            }}
             placeholder="GROWI"
+            {...register('title')}
           />
           <p className="form-text text-muted">{t('admin:app_setting.sitename_change')}</p>
         </div>
@@ -60,11 +94,8 @@ const AppSetting = (props) => {
           <input
             className="form-control"
             type="text"
-            value={adminAppContainer.state.confidential || ''}
-            onChange={(e) => {
-              adminAppContainer.changeConfidential(e.target.value);
-            }}
             placeholder={t('admin:app_setting.confidential_example')}
+            {...register('confidential')}
           />
           <p className="form-text text-muted">{t('admin:app_setting.header_content')}</p>
         </div>
@@ -88,12 +119,8 @@ const AppSetting = (props) => {
                     type="radio"
                     id={`radioLang${locale}`}
                     className="form-check-input"
-                    name="globalLang"
                     value={locale}
-                    checked={adminAppContainer.state.globalLang === locale}
-                    onChange={(e) => {
-                      adminAppContainer.changeGlobalLang(e.target.value);
-                    }}
+                    {...register('globalLang')}
                   />
                   <label className="form-label form-check-label" htmlFor={`radioLang${locale}`}>{fixedT('meta.display_name')}</label>
                 </div>
@@ -116,9 +143,8 @@ const AppSetting = (props) => {
               type="radio"
               id="radio-email-show"
               className="form-check-input"
-              name="mailVisibility"
-              checked={adminAppContainer.state.isEmailPublishedForNewUser === true}
-              onChange={() => { adminAppContainer.changeIsEmailPublishedForNewUserShow(true) }}
+              value="true"
+              {...register('isEmailPublishedForNewUser')}
             />
             <label className="form-label form-check-label" htmlFor="radio-email-show">{t('commons:Show')}</label>
           </div>
@@ -128,9 +154,8 @@ const AppSetting = (props) => {
               type="radio"
               id="radio-email-hide"
               className="form-check-input"
-              name="mailVisibility"
-              checked={adminAppContainer.state.isEmailPublishedForNewUser === false}
-              onChange={() => { adminAppContainer.changeIsEmailPublishedForNewUserShow(false) }}
+              value="false"
+              {...register('isEmailPublishedForNewUser')}
             />
             <label className="form-label form-check-label" htmlFor="radio-email-hide">{t('commons:Hide')}</label>
           </div>
@@ -150,11 +175,7 @@ const AppSetting = (props) => {
               type="checkbox"
               id="cbFileUpload"
               className="form-check-input"
-              name="fileUpload"
-              checked={adminAppContainer.state.fileUpload}
-              onChange={(e) => {
-                adminAppContainer.changeFileUpload(e.target.checked);
-              }}
+              {...register('fileUpload')}
             />
             <label
               className="form-label form-check-label"
@@ -170,8 +191,8 @@ const AppSetting = (props) => {
         </div>
       </div>
 
-      <AdminUpdateButtonRow onClick={submitHandler} disabled={adminAppContainer.state.retrieveError != null} />
-    </React.Fragment>
+      <AdminUpdateButtonRow type="submit" disabled={adminAppContainer.state.retrieveError != null} />
+    </form>
   );
 
 };

+ 7 - 19
apps/app/src/client/components/Admin/App/AwsSetting.tsx

@@ -1,9 +1,11 @@
 import type { JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import type { UseFormRegister, FieldValues } from 'react-hook-form';
 
 
 export type AwsSettingMoleculeProps = {
+  register: UseFormRegister<FieldValues>
   s3ReferenceFileWithRelayMode
   s3Region
   s3CustomEndpoint
@@ -76,10 +78,7 @@ export const AwsSettingMolecule = (props: AwsSettingMoleculeProps): JSX.Element
           <input
             className="form-control"
             placeholder={`${t('eg')} ap-northeast-1`}
-            value={props.s3Region || ''}
-            onChange={(e) => {
-              props?.onChangeS3Region(e.target.value);
-            }}
+            {...props.register('s3Region')}
           />
         </div>
       </div>
@@ -93,10 +92,7 @@ export const AwsSettingMolecule = (props: AwsSettingMoleculeProps): JSX.Element
             className="form-control"
             type="text"
             placeholder={`${t('eg')} http://localhost:9000`}
-            value={props.s3CustomEndpoint || ''}
-            onChange={(e) => {
-              props?.onChangeS3CustomEndpoint(e.target.value);
-            }}
+            {...props.register('s3CustomEndpoint')}
           />
           <p className="form-text text-muted">{t('admin:app_setting.custom_endpoint_change')}</p>
         </div>
@@ -111,10 +107,7 @@ export const AwsSettingMolecule = (props: AwsSettingMoleculeProps): JSX.Element
             className="form-control"
             type="text"
             placeholder={`${t('eg')} crowi`}
-            value={props.s3Bucket || ''}
-            onChange={(e) => {
-              props.onChangeS3Bucket(e.target.value);
-            }}
+            {...props.register('s3Bucket')}
           />
         </div>
       </div>
@@ -127,10 +120,7 @@ export const AwsSettingMolecule = (props: AwsSettingMoleculeProps): JSX.Element
           <input
             className="form-control"
             type="text"
-            value={props.s3AccessKeyId || ''}
-            onChange={(e) => {
-              props?.onChangeS3AccessKeyId(e.target.value);
-            }}
+            {...props.register('s3AccessKeyId')}
           />
         </div>
       </div>
@@ -143,9 +133,7 @@ export const AwsSettingMolecule = (props: AwsSettingMoleculeProps): JSX.Element
           <input
             className="form-control"
             type="text"
-            onChange={(e) => {
-              props?.onChangeS3SecretAccessKey(e.target.value);
-            }}
+            {...props.register('s3SecretAccessKey')}
           />
           <p className="form-text text-muted">{t('admin:app_setting.s3_secret_access_key_input_description')}</p>
         </div>

+ 10 - 20
apps/app/src/client/components/Admin/App/AzureSetting.tsx

@@ -1,11 +1,13 @@
 import type { JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import type { UseFormRegister, FieldValues } from 'react-hook-form';
 
 import MaskedInput from './MaskedInput';
 
 
 export type AzureSettingMoleculeProps = {
+  register: UseFormRegister<FieldValues>
   azureReferenceFileWithRelayMode
   azureUseOnlyEnvVars
   azureTenantId
@@ -32,15 +34,10 @@ export const AzureSettingMolecule = (props: AzureSettingMoleculeProps): JSX.Elem
   const {
     azureReferenceFileWithRelayMode,
     azureUseOnlyEnvVars,
-    azureTenantId,
-    azureClientId,
-    azureClientSecret,
-    azureStorageAccountName,
     envAzureTenantId,
     envAzureClientId,
     envAzureClientSecret,
     envAzureStorageAccountName,
-    azureStorageContainerName,
     envAzureStorageContainerName,
   } = props;
 
@@ -116,10 +113,9 @@ export const AzureSettingMolecule = (props: AzureSettingMoleculeProps): JSX.Elem
             <th>{t('admin:app_setting.azure_tenant_id')}</th>
             <td>
               <MaskedInput
-                name="azureTenantId"
+                register={props.register}
+                fieldName="azureTenantId"
                 readOnly={azureUseOnlyEnvVars}
-                value={azureTenantId}
-                onChange={e => props?.onChangeAzureTenantId(e.target.value)}
               />
             </td>
             <td>
@@ -134,10 +130,9 @@ export const AzureSettingMolecule = (props: AzureSettingMoleculeProps): JSX.Elem
             <th>{t('admin:app_setting.azure_client_id')}</th>
             <td>
               <MaskedInput
-                name="azureClientId"
+                register={props.register}
+                fieldName="azureClientId"
                 readOnly={azureUseOnlyEnvVars}
-                value={azureClientId}
-                onChange={e => props?.onChangeAzureClientId(e.target.value)}
               />
             </td>
             <td>
@@ -152,10 +147,9 @@ export const AzureSettingMolecule = (props: AzureSettingMoleculeProps): JSX.Elem
             <th>{t('admin:app_setting.azure_client_secret')}</th>
             <td>
               <MaskedInput
-                name="azureClientSecret"
+                register={props.register}
+                fieldName="azureClientSecret"
                 readOnly={azureUseOnlyEnvVars}
-                value={azureClientSecret}
-                onChange={e => props?.onChangeAzureClientSecret(e.target.value)}
               />
             </td>
             <td>
@@ -172,10 +166,8 @@ export const AzureSettingMolecule = (props: AzureSettingMoleculeProps): JSX.Elem
               <input
                 className="form-control"
                 type="text"
-                name="azureStorageAccountName"
                 readOnly={azureUseOnlyEnvVars}
-                value={azureStorageAccountName}
-                onChange={e => props?.onChangeAzureStorageAccountName(e.target.value)}
+                {...props.register('azureStorageAccountName')}
               />
             </td>
             <td>
@@ -192,10 +184,8 @@ export const AzureSettingMolecule = (props: AzureSettingMoleculeProps): JSX.Elem
               <input
                 className="form-control"
                 type="text"
-                name="azureStorageContainerName"
                 readOnly={azureUseOnlyEnvVars}
-                value={azureStorageContainerName}
-                onChange={e => props?.onChangeAzureStorageContainerName(e.target.value)}
+                {...props.register('azureStorageContainerName')}
               />
             </td>
             <td>

+ 53 - 6
apps/app/src/client/components/Admin/App/FileUploadSetting.tsx

@@ -1,7 +1,8 @@
 import type { ChangeEvent, JSX } from 'react';
-import React, { useCallback } from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 
 import AdminAppContainer from '~/client/services/AdminAppContainer';
 import { toastSuccess, toastError } from '~/client/util/toastr';
@@ -22,7 +23,8 @@ type FileUploadSettingMoleculeProps = {
   isFixedFileUploadByEnvVar: boolean
   envFileUploadType?: string
   onChangeFileUploadType: (e: ChangeEvent, type: string) => void
-} & AwsSettingMoleculeProps & GcsSettingMoleculeProps & AzureSettingMoleculeProps;
+  register: ReturnType<typeof useForm>['register']
+} & Omit<AwsSettingMoleculeProps, 'register'> & Omit<GcsSettingMoleculeProps, 'register'> & Omit<AzureSettingMoleculeProps, 'register'>;
 
 export const FileUploadSettingMolecule = React.memo((props: FileUploadSettingMoleculeProps): JSX.Element => {
   const { t } = useTranslation(['admin', 'commons']);
@@ -78,6 +80,7 @@ export const FileUploadSettingMolecule = React.memo((props: FileUploadSettingMol
 
       {props.fileUploadType === 'aws' && (
         <AwsSettingMolecule
+          register={props.register}
           s3ReferenceFileWithRelayMode={props.s3ReferenceFileWithRelayMode}
           s3Region={props.s3Region}
           s3CustomEndpoint={props.s3CustomEndpoint}
@@ -94,6 +97,7 @@ export const FileUploadSettingMolecule = React.memo((props: FileUploadSettingMol
       )}
       {props.fileUploadType === 'gcs' && (
         <GcsSettingMolecule
+          register={props.register}
           gcsReferenceFileWithRelayMode={props.gcsReferenceFileWithRelayMode}
           gcsUseOnlyEnvVars={props.gcsUseOnlyEnvVars}
           gcsApiKeyJsonPath={props.gcsApiKeyJsonPath}
@@ -110,6 +114,7 @@ export const FileUploadSettingMolecule = React.memo((props: FileUploadSettingMol
       )}
       {props.fileUploadType === 'azure' && (
         <AzureSettingMolecule
+          register={props.register}
           azureReferenceFileWithRelayMode={props.azureReferenceFileWithRelayMode}
           azureUseOnlyEnvVars={props.azureUseOnlyEnvVars}
           azureTenantId={props.azureTenantId}
@@ -159,8 +164,49 @@ const FileUploadSetting = (props: FileUploadSettingProps): JSX.Element => {
     envAzureStorageAccountName, envAzureStorageContainerName,
   } = adminAppContainer.state;
 
-  const submitHandler = useCallback(async() => {
+  const { register, handleSubmit, reset } = useForm();
+
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      s3Region,
+      s3CustomEndpoint,
+      s3Bucket,
+      s3AccessKeyId,
+      gcsApiKeyJsonPath,
+      gcsBucket,
+      gcsUploadNamespace,
+      azureTenantId,
+      azureClientId,
+      azureClientSecret,
+      azureStorageAccountName,
+      azureStorageContainerName,
+    });
+  }, [
+    reset,
+    s3Region, s3CustomEndpoint, s3Bucket, s3AccessKeyId,
+    gcsApiKeyJsonPath, gcsBucket, gcsUploadNamespace,
+    azureTenantId, azureClientId, azureClientSecret,
+    azureStorageAccountName, azureStorageContainerName,
+  ]);
+
+  const submitHandler = useCallback(async(data) => {
     try {
+      // Update container state with form data
+      await adminAppContainer.changeS3Region(data.s3Region ?? '');
+      await adminAppContainer.changeS3CustomEndpoint(data.s3CustomEndpoint ?? '');
+      await adminAppContainer.changeS3Bucket(data.s3Bucket ?? '');
+      await adminAppContainer.changeS3AccessKeyId(data.s3AccessKeyId ?? '');
+      await adminAppContainer.changeS3SecretAccessKey(data.s3SecretAccessKey ?? '');
+      await adminAppContainer.changeGcsApiKeyJsonPath(data.gcsApiKeyJsonPath ?? '');
+      await adminAppContainer.changeGcsBucket(data.gcsBucket ?? '');
+      await adminAppContainer.changeGcsUploadNamespace(data.gcsUploadNamespace ?? '');
+      await adminAppContainer.changeAzureTenantId(data.azureTenantId ?? '');
+      await adminAppContainer.changeAzureClientId(data.azureClientId ?? '');
+      await adminAppContainer.changeAzureClientSecret(data.azureClientSecret ?? '');
+      await adminAppContainer.changeAzureStorageAccountName(data.azureStorageAccountName ?? '');
+      await adminAppContainer.changeAzureStorageContainerName(data.azureStorageContainerName ?? '');
+
       await adminAppContainer.updateFileUploadSettingHandler();
       toastSuccess(t('toaster.update_successed', { target: t('admin:app_setting.file_upload_settings'), ns: 'commons' }));
     }
@@ -241,8 +287,9 @@ const FileUploadSetting = (props: FileUploadSettingProps): JSX.Element => {
   }, [adminAppContainer]);
 
   return (
-    <>
+    <form onSubmit={handleSubmit(submitHandler)}>
       <FileUploadSettingMolecule
+        register={register}
         fileUploadType={fileUploadType}
         isFixedFileUploadByEnvVar={isFixedFileUploadByEnvVar}
         envFileUploadType={envFileUploadType}
@@ -290,8 +337,8 @@ const FileUploadSetting = (props: FileUploadSettingProps): JSX.Element => {
         onChangeAzureStorageAccountName={onChangeAzureStorageAccountNameHandler}
         onChangeAzureStorageContainerName={onChangeAzureStorageContainerNameHandler}
       />
-      <AdminUpdateButtonRow onClick={submitHandler} disabled={retrieveError != null} />
-    </>
+      <AdminUpdateButtonRow disabled={retrieveError != null} />
+    </form>
   );
 };
 

+ 5 - 12
apps/app/src/client/components/Admin/App/GcsSetting.tsx

@@ -1,9 +1,11 @@
 import type { JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import type { UseFormRegister, FieldValues } from 'react-hook-form';
 
 
 export type GcsSettingMoleculeProps = {
+  register: UseFormRegister<FieldValues>
   gcsReferenceFileWithRelayMode
   gcsUseOnlyEnvVars
   gcsApiKeyJsonPath
@@ -24,11 +26,8 @@ export const GcsSettingMolecule = (props: GcsSettingMoleculeProps): JSX.Element
   const {
     gcsReferenceFileWithRelayMode,
     gcsUseOnlyEnvVars,
-    gcsApiKeyJsonPath,
     envGcsApiKeyJsonPath,
-    gcsBucket,
     envGcsBucket,
-    gcsUploadNamespace,
     envGcsUploadNamespace,
   } = props;
 
@@ -106,10 +105,8 @@ export const GcsSettingMolecule = (props: GcsSettingMoleculeProps): JSX.Element
               <input
                 className="form-control"
                 type="text"
-                name="gcsApiKeyJsonPath"
                 readOnly={gcsUseOnlyEnvVars}
-                value={gcsApiKeyJsonPath}
-                onChange={e => props?.onChangeGcsApiKeyJsonPath(e.target.value)}
+                {...props.register('gcsApiKeyJsonPath')}
               />
             </td>
             <td>
@@ -126,10 +123,8 @@ export const GcsSettingMolecule = (props: GcsSettingMoleculeProps): JSX.Element
               <input
                 className="form-control"
                 type="text"
-                name="gcsBucket"
                 readOnly={gcsUseOnlyEnvVars}
-                value={gcsBucket}
-                onChange={e => props?.onChangeGcsBucket(e.target.value)}
+                {...props.register('gcsBucket')}
               />
             </td>
             <td>
@@ -146,10 +141,8 @@ export const GcsSettingMolecule = (props: GcsSettingMoleculeProps): JSX.Element
               <input
                 className="form-control"
                 type="text"
-                name="gcsUploadNamespace"
                 readOnly={gcsUseOnlyEnvVars}
-                value={gcsUploadNamespace}
-                onChange={e => props?.onChangeGcsUploadNamespace(e.target.value)}
+                {...props.register('gcsUploadNamespace')}
               />
             </td>
             <td>

+ 56 - 17
apps/app/src/client/components/Admin/App/MailSetting.tsx

@@ -1,14 +1,15 @@
-import React from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 
 import AdminAppContainer from '~/client/services/AdminAppContainer';
 import { toastSuccess, toastError } from '~/client/util/toastr';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
 
-import SesSetting from './SesSetting';
-import SmtpSetting from './SmtpSetting';
+import { SesSetting } from './SesSetting';
+import { SmtpSetting } from './SmtpSetting';
 
 
 type Props = {
@@ -22,15 +23,57 @@ const MailSetting = (props: Props) => {
 
   const transmissionMethods = ['smtp', 'ses'];
 
-  async function submitHandler() {
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
+
+  // Reset form when adminAppContainer state changes
+  useEffect(() => {
+    reset({
+      fromAddress: adminAppContainer.state.fromAddress || '',
+      transmissionMethod: adminAppContainer.state.transmissionMethod || 'smtp',
+      smtpHost: adminAppContainer.state.smtpHost || '',
+      smtpPort: adminAppContainer.state.smtpPort || '',
+      smtpUser: adminAppContainer.state.smtpUser || '',
+      smtpPassword: adminAppContainer.state.smtpPassword || '',
+      sesAccessKeyId: adminAppContainer.state.sesAccessKeyId || '',
+      sesSecretAccessKey: adminAppContainer.state.sesSecretAccessKey || '',
+    });
+  }, [
+    adminAppContainer.state.fromAddress,
+    adminAppContainer.state.transmissionMethod,
+    adminAppContainer.state.smtpHost,
+    adminAppContainer.state.smtpPort,
+    adminAppContainer.state.smtpUser,
+    adminAppContainer.state.smtpPassword,
+    adminAppContainer.state.sesAccessKeyId,
+    adminAppContainer.state.sesSecretAccessKey,
+    reset,
+  ]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
+      // Await all setState completions before API call
+      await Promise.all([
+        adminAppContainer.changeFromAddress(data.fromAddress),
+        adminAppContainer.changeTransmissionMethod(data.transmissionMethod),
+        adminAppContainer.changeSmtpHost(data.smtpHost),
+        adminAppContainer.changeSmtpPort(data.smtpPort),
+        adminAppContainer.changeSmtpUser(data.smtpUser),
+        adminAppContainer.changeSmtpPassword(data.smtpPassword),
+        adminAppContainer.changeSesAccessKeyId(data.sesAccessKeyId),
+        adminAppContainer.changeSesSecretAccessKey(data.sesSecretAccessKey),
+      ]);
+
       await adminAppContainer.updateMailSettingHandler();
       toastSuccess(t('toaster.update_successed', { target: t('admin:app_setting.mail_settings'), ns: 'commons' }));
     }
     catch (err) {
       toastError(err);
     }
-  }
+  }, [adminAppContainer, t]);
 
   async function sendTestEmailHandler() {
     const { adminAppContainer } = props;
@@ -45,7 +88,7 @@ const MailSetting = (props: Props) => {
 
 
   return (
-    <React.Fragment>
+    <form onSubmit={handleSubmit(onSubmit)}>
       {!adminAppContainer.state.isMailerSetup && (
         <div className="alert alert-danger"><span className="material-symbols-outlined">error</span> {t('admin:app_setting.mailer_is_not_set_up')}</div>
       )}
@@ -56,8 +99,7 @@ const MailSetting = (props: Props) => {
             className="form-control"
             type="text"
             placeholder={`${t('eg')} mail@growi.org`}
-            value={adminAppContainer.state.fromAddress || ''}
-            onChange={(e) => { adminAppContainer.changeFromAddress(e.target.value) }}
+            {...register('fromAddress')}
           />
         </div>
       </div>
@@ -73,12 +115,9 @@ const MailSetting = (props: Props) => {
                 <input
                   type="radio"
                   className="form-check-input"
-                  name="transmission-method"
                   id={`transmission-method-radio-${method}`}
-                  checked={adminAppContainer.state.transmissionMethod === method}
-                  onChange={(e) => {
-                    adminAppContainer.changeTransmissionMethod(method);
-                  }}
+                  value={method}
+                  {...register('transmissionMethod')}
                 />
                 <label className="form-label form-check-label" htmlFor={`transmission-method-radio-${method}`}>{t(`admin:app_setting.${method}_label`)}</label>
               </div>
@@ -87,12 +126,12 @@ const MailSetting = (props: Props) => {
         </div>
       </div>
 
-      {adminAppContainer.state.transmissionMethod === 'smtp' && <SmtpSetting />}
-      {adminAppContainer.state.transmissionMethod === 'ses' && <SesSetting />}
+      {adminAppContainer.state.transmissionMethod === 'smtp' && <SmtpSetting register={register} />}
+      {adminAppContainer.state.transmissionMethod === 'ses' && <SesSetting register={register} />}
 
       <div className="row my-3">
         <div className="mx-auto">
-          <button type="button" className="btn btn-primary" onClick={submitHandler} disabled={adminAppContainer.state.retrieveError != null}>
+          <button type="submit" className="btn btn-primary" disabled={adminAppContainer.state.retrieveError != null}>
             { t('Update') }
           </button>
           {adminAppContainer.state.transmissionMethod === 'smtp' && (
@@ -102,7 +141,7 @@ const MailSetting = (props: Props) => {
           )}
         </div>
       </div>
-    </React.Fragment>
+    </form>
   );
 
 };

+ 19 - 7
apps/app/src/client/components/Admin/App/MaskedInput.tsx

@@ -1,13 +1,18 @@
+import type { ChangeEvent } from 'react';
 import { useState, type JSX } from 'react';
 
+import type { UseFormRegister, FieldValues } from 'react-hook-form';
+
 import styles from './MaskedInput.module.scss';
 
 type Props = {
-  name: string
+  name?: string
   readOnly: boolean
-  value: string
-  onChange?: (e: any) => void
+  value?: string
+  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
   tabIndex?: number | undefined
+  register?: UseFormRegister<FieldValues>
+  fieldName?: string
 };
 
 export default function MaskedInput(props: Props): JSX.Element {
@@ -17,19 +22,26 @@ export default function MaskedInput(props: Props): JSX.Element {
   };
 
   const {
-    name, readOnly, value, onChange, tabIndex,
+    name, readOnly, value, onChange, tabIndex, register, fieldName,
   } = props;
 
+  // Use register if provided, otherwise use value/onChange
+  const inputProps = register && fieldName
+    ? register(fieldName)
+    : {
+      name,
+      value,
+      onChange,
+    };
+
   return (
     <div className={styles.MaskedInput}>
       <input
         className="form-control"
         type={passwordShown ? 'text' : 'password'}
-        name={name}
         readOnly={readOnly}
-        value={value}
-        onChange={onChange}
         tabIndex={tabIndex}
+        {...inputProps}
       />
       <span onClick={togglePassword} className={styles.PasswordReveal}>
         {passwordShown ? (

+ 14 - 14
apps/app/src/client/components/Admin/App/SesSetting.tsx

@@ -1,20 +1,24 @@
 
 import React from 'react';
 
+import type { UseFormRegister } from 'react-hook-form';
+
 import AdminAppContainer from '~/client/services/AdminAppContainer';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
 
 type Props = {
-  adminAppContainer: AdminAppContainer,
+  adminAppContainer?: AdminAppContainer,
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  register: UseFormRegister<any>,
 }
 
-const SmtpSetting = (props: Props) => {
-  const { adminAppContainer } = props;
+const SesSetting = (props: Props): JSX.Element => {
+  const { register } = props;
 
   return (
     <React.Fragment>
-      <div id="mail-smtp" className="tab-pane active mt-5">
+      <div id="mail-ses" className="tab-pane active mt-5">
 
         <div className="row">
           <label className="text-start text-md-end col-md-3 col-form-label">
@@ -24,10 +28,7 @@ const SmtpSetting = (props: Props) => {
             <input
               className="form-control"
               type="text"
-              value={adminAppContainer.state.sesAccessKeyId || ''}
-              onChange={(e) => {
-                adminAppContainer.changeSesAccessKeyId(e.target.value);
-              }}
+              {...register('sesAccessKeyId')}
             />
           </div>
         </div>
@@ -40,10 +41,7 @@ const SmtpSetting = (props: Props) => {
             <input
               className="form-control"
               type="text"
-              value={adminAppContainer.state.sesSecretAccessKey || ''}
-              onChange={(e) => {
-                adminAppContainer.changeSesSecretAccessKey(e.target.value);
-              }}
+              {...register('sesSecretAccessKey')}
             />
           </div>
         </div>
@@ -53,9 +51,11 @@ const SmtpSetting = (props: Props) => {
   );
 };
 
+export { SesSetting };
+
 /**
  * Wrapper component for using unstated
  */
-const SmtpSettingWrapper = withUnstatedContainers(SmtpSetting, [AdminAppContainer]);
+const SesSettingWrapper = withUnstatedContainers(SesSetting, [AdminAppContainer]);
 
-export default SmtpSettingWrapper;
+export default SesSettingWrapper;

+ 22 - 9
apps/app/src/client/components/Admin/App/SiteUrlSetting.tsx

@@ -1,6 +1,7 @@
-import React, { useCallback } from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 
 import AdminAppContainer from '~/client/services/AdminAppContainer';
 import { toastSuccess, toastError } from '~/client/util/toastr';
@@ -21,9 +22,23 @@ const SiteUrlSetting = (props: Props) => {
   const { t: tCommon } = useTranslation('commons');
   const { adminAppContainer } = props;
 
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
 
-  const submitHandler = useCallback(async() => {
+  // Reset form when adminAppContainer state changes
+  useEffect(() => {
+    reset({
+      siteUrl: adminAppContainer.state.siteUrl || '',
+    });
+  }, [adminAppContainer.state.siteUrl, reset]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
+      // Await setState completion before API call
+      await adminAppContainer.changeSiteUrl(data.siteUrl);
       await adminAppContainer.updateSiteUrlSettingHandler();
       toastSuccess(tCommon('toaster.update_successed', { target: t('site_url.title') }));
     }
@@ -34,7 +49,7 @@ const SiteUrlSetting = (props: Props) => {
   }, [adminAppContainer, t, tCommon]);
 
   return (
-    <React.Fragment>
+    <form onSubmit={handleSubmit(onSubmit)}>
       <p className="card custom-card bg-body-tertiary">{t('site_url.desc')}</p>
       {!adminAppContainer.state.isSetSiteUrl
           && (<p className="alert alert-danger"><span className="material-symbols-outlined">error</span> {t('site_url.warn')}</p>)}
@@ -69,11 +84,9 @@ const SiteUrlSetting = (props: Props) => {
                 <input
                   className="form-control"
                   type="text"
-                  name="settingForm[app:siteUrl]"
-                  value={adminAppContainer.state.siteUrl || ''}
-                  disabled={adminAppContainer.state.siteUrlUseOnlyEnvVars ?? true}
-                  onChange={(e) => { adminAppContainer.changeSiteUrl(e.target.value) }}
+                  readOnly={adminAppContainer.state.siteUrlUseOnlyEnvVars ?? true}
                   placeholder="e.g. https://my.growi.org"
+                  {...register('siteUrl')}
                 />
                 <p className="form-text text-muted">
                   {/* eslint-disable-next-line react/no-danger */}
@@ -92,8 +105,8 @@ const SiteUrlSetting = (props: Props) => {
         </table>
       </div>
 
-      <AdminUpdateButtonRow onClick={submitHandler} disabled={adminAppContainer.state.retrieveError != null} />
-    </React.Fragment>
+      <AdminUpdateButtonRow type="submit" disabled={adminAppContainer.state.retrieveError != null} />
+    </form>
   );
 };
 

+ 12 - 11
apps/app/src/client/components/Admin/App/SmtpSetting.tsx

@@ -2,6 +2,7 @@
 import React from 'react';
 
 import { useTranslation } from 'next-i18next';
+import type { UseFormRegister } from 'react-hook-form';
 
 import AdminAppContainer from '~/client/services/AdminAppContainer';
 
@@ -9,12 +10,14 @@ import { withUnstatedContainers } from '../../UnstatedUtils';
 
 
 type Props = {
-  adminAppContainer: AdminAppContainer,
+  adminAppContainer?: AdminAppContainer,
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  register: UseFormRegister<any>,
 }
 
-const SmtpSetting = (props: Props) => {
+const SmtpSetting = (props: Props): JSX.Element => {
   const { t } = useTranslation();
-  const { adminAppContainer } = props;
+  const { register } = props;
 
   return (
     <React.Fragment>
@@ -27,8 +30,7 @@ const SmtpSetting = (props: Props) => {
             <input
               className="form-control"
               type="text"
-              value={adminAppContainer.state.smtpHost || ''}
-              onChange={(e) => { adminAppContainer.changeSmtpHost(e.target.value) }}
+              {...register('smtpHost')}
             />
           </div>
         </div>
@@ -40,8 +42,7 @@ const SmtpSetting = (props: Props) => {
           <div className="col-md-6">
             <input
               className="form-control"
-              value={adminAppContainer.state.smtpPort || ''}
-              onChange={(e) => { adminAppContainer.changeSmtpPort(e.target.value) }}
+              {...register('smtpPort')}
             />
           </div>
         </div>
@@ -54,8 +55,7 @@ const SmtpSetting = (props: Props) => {
             <input
               className="form-control"
               type="text"
-              value={adminAppContainer.state.smtpUser || ''}
-              onChange={(e) => { adminAppContainer.changeSmtpUser(e.target.value) }}
+              {...register('smtpUser')}
             />
           </div>
         </div>
@@ -68,8 +68,7 @@ const SmtpSetting = (props: Props) => {
             <input
               className="form-control"
               type="password"
-              value={adminAppContainer.state.smtpPassword || ''}
-              onChange={(e) => { adminAppContainer.changeSmtpPassword(e.target.value) }}
+              {...register('smtpPassword')}
             />
           </div>
         </div>
@@ -78,6 +77,8 @@ const SmtpSetting = (props: Props) => {
   );
 };
 
+export { SmtpSetting };
+
 /**
  * Wrapper component for using unstated
  */

+ 11 - 2
apps/app/src/client/components/Admin/Common/AdminUpdateButtonRow.tsx

@@ -3,8 +3,9 @@ import React, { type JSX } from 'react';
 import { useTranslation } from 'next-i18next';
 
 type Props = {
-  onClick: () => void,
+  onClick?: () => void,
   disabled?: boolean,
+  type?: 'button' | 'submit' | 'reset',
 }
 
 const AdminUpdateButtonRow = (props: Props): JSX.Element => {
@@ -13,7 +14,15 @@ const AdminUpdateButtonRow = (props: Props): JSX.Element => {
   return (
     <div className="row my-3">
       <div className="mx-auto">
-        <button type="button" className="btn btn-primary" onClick={props.onClick} disabled={props.disabled ?? false}>{ t('Update') }</button>
+        <button
+          // eslint-disable-next-line react/button-has-type
+          type={props.type ?? 'button'}
+          className="btn btn-primary"
+          onClick={props.onClick}
+          disabled={props.disabled ?? false}
+        >
+          { t('Update') }
+        </button>
       </div>
     </div>
   );

+ 29 - 13
apps/app/src/client/components/Admin/Customize/CustomizeCssSetting.tsx

@@ -1,6 +1,7 @@
-import React, { useCallback, type JSX } from 'react';
+import React, { useCallback, useEffect, type JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 import { Card, CardBody } from 'reactstrap';
 
 import AdminCustomizeContainer from '~/client/services/AdminCustomizeContainer';
@@ -18,8 +19,23 @@ const CustomizeCssSetting = (props: Props): JSX.Element => {
   const { adminCustomizeContainer } = props;
   const { t } = useTranslation();
 
-  const onClickSubmit = useCallback(async() => {
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
+
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      customizeCss: adminCustomizeContainer.state.currentCustomizeCss || '',
+    });
+  }, [adminCustomizeContainer.state.currentCustomizeCss, reset]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
+      // Update container state before API call
+      await adminCustomizeContainer.changeCustomizeCss(data.customizeCss);
       await adminCustomizeContainer.updateCustomizeCss();
       toastSuccess(t('toaster.update_successed', { target: t('admin:customize_settings.custom_css'), ns: 'commons' }));
     }
@@ -41,17 +57,17 @@ const CustomizeCssSetting = (props: Props): JSX.Element => {
             </CardBody>
           </Card>
 
-          <div>
-            <textarea
-              className="form-control"
-              name="customizeCss"
-              rows={8}
-              value={adminCustomizeContainer.state.currentCustomizeCss || ''}
-              onChange={(e) => { adminCustomizeContainer.changeCustomizeCss(e.target.value) }}
-            />
-          </div>
-
-          <AdminUpdateButtonRow onClick={onClickSubmit} disabled={adminCustomizeContainer.state.retrieveError != null} />
+          <form onSubmit={handleSubmit(onSubmit)}>
+            <div>
+              <textarea
+                className="form-control"
+                rows={8}
+                {...register('customizeCss')}
+              />
+            </div>
+
+            <AdminUpdateButtonRow type="submit" disabled={adminCustomizeContainer.state.retrieveError != null} />
+          </form>
         </div>
       </div>
     </React.Fragment>

+ 47 - 31
apps/app/src/client/components/Admin/Customize/CustomizeNoscriptSetting.tsx

@@ -1,6 +1,7 @@
-import React, { useCallback, type JSX } from 'react';
+import React, { useCallback, useEffect, type JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 import { PrismAsyncLight } from 'react-syntax-highlighter';
 import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
 import { Card, CardBody } from 'reactstrap';
@@ -20,8 +21,23 @@ const CustomizeNoscriptSetting = (props: Props): JSX.Element => {
   const { adminCustomizeContainer } = props;
   const { t } = useTranslation();
 
-  const onClickSubmit = useCallback(async() => {
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
+
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      customizeNoscript: adminCustomizeContainer.state.currentCustomizeNoscript || '',
+    });
+  }, [adminCustomizeContainer.state.currentCustomizeNoscript, reset]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
+      // Update container state before API call
+      await adminCustomizeContainer.changeCustomizeNoscript(data.customizeNoscript);
       await adminCustomizeContainer.updateCustomizeNoscript();
       toastSuccess(t('toaster.update_successed', { target: t('admin:customize_settings.custom_noscript'), ns: 'commons' }));
     }
@@ -45,40 +61,40 @@ const CustomizeNoscriptSetting = (props: Props): JSX.Element => {
             </CardBody>
           </Card>
 
-          <div>
-            <textarea
-              className="form-control mb-2"
-              name="customizeNoscript"
-              rows={8}
-              value={adminCustomizeContainer.state.currentCustomizeNoscript || ''}
-              onChange={(e) => { adminCustomizeContainer.changeCustomizeNoscript(e.target.value) }}
-            />
-          </div>
-
-          <a
-            className="text-muted"
-            data-bs-toggle="collapse"
-            href="#collapseExampleHtml"
-            role="button"
-            aria-expanded="false"
-            aria-controls="collapseExampleHtml"
-          >
-            <span className="material-symbols-outlined me-1" aria-hidden="true">navigate_next</span>
-            Example for Google Tag Manager
-          </a>
-          <div className="collapse" id="collapseExampleHtml">
-            <PrismAsyncLight
-              style={oneDark}
-              language="javascript"
+          <form onSubmit={handleSubmit(onSubmit)}>
+            <div>
+              <textarea
+                className="form-control mb-2"
+                rows={8}
+                {...register('customizeNoscript')}
+              />
+            </div>
+
+            <a
+              className="text-muted"
+              data-bs-toggle="collapse"
+              href="#collapseExampleHtml"
+              role="button"
+              aria-expanded="false"
+              aria-controls="collapseExampleHtml"
             >
-              {`<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
+              <span className="material-symbols-outlined me-1" aria-hidden="true">navigate_next</span>
+              Example for Google Tag Manager
+            </a>
+            <div className="collapse" id="collapseExampleHtml">
+              <PrismAsyncLight
+                style={oneDark}
+                language="javascript"
+              >
+                {`<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
   height="0"
   width="0"
   style="display:none;visibility:hidden"></iframe>`}
-            </PrismAsyncLight>
-          </div>
+              </PrismAsyncLight>
+            </div>
 
-          <AdminUpdateButtonRow onClick={onClickSubmit} disabled={adminCustomizeContainer.state.retrieveError != null} />
+            <AdminUpdateButtonRow type="submit" disabled={adminCustomizeContainer.state.retrieveError != null} />
+          </form>
         </div>
       </div>
     </React.Fragment>

+ 47 - 31
apps/app/src/client/components/Admin/Customize/CustomizeScriptSetting.tsx

@@ -1,6 +1,7 @@
-import React, { useCallback, type JSX } from 'react';
+import React, { useCallback, useEffect, type JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 import { PrismAsyncLight } from 'react-syntax-highlighter';
 import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
 import { Card, CardBody } from 'reactstrap';
@@ -20,8 +21,23 @@ const CustomizeScriptSetting = (props: Props): JSX.Element => {
   const { adminCustomizeContainer } = props;
   const { t } = useTranslation();
 
-  const onClickSubmit = useCallback(async() => {
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
+
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      customizeScript: adminCustomizeContainer.state.currentCustomizeScript || '',
+    });
+  }, [adminCustomizeContainer.state.currentCustomizeScript, reset]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
+      // Update container state before API call
+      await adminCustomizeContainer.changeCustomizeScript(data.customizeScript);
       await adminCustomizeContainer.updateCustomizeScript();
       toastSuccess(t('toaster.update_successed', { target: t('admin:customize_settings.custom_script'), ns: 'commons' }));
     }
@@ -42,33 +58,32 @@ const CustomizeScriptSetting = (props: Props): JSX.Element => {
             </CardBody>
           </Card>
 
-          <div>
-            <textarea
-              className="form-control mb-2"
-              name="customizeScript"
-              rows={8}
-              value={adminCustomizeContainer.state.currentCustomizeScript || ''}
-              onChange={(e) => { adminCustomizeContainer.changeCustomizeScript(e.target.value) }}
-            />
-          </div>
-
-          <a
-            className="text-muted"
-            data-bs-toggle="collapse"
-            href="#collapseExampleScript"
-            role="button"
-            aria-expanded="false"
-            aria-controls="collapseExampleScript"
-          >
-            <span className="material-symbols-outlined me-1" aria-hidden="true">navigate_next</span>
-            Example for Google Tag Manager
-          </a>
-          <div className="collapse" id="collapseExampleScript">
-            <PrismAsyncLight
-              style={oneDark}
-              language="javascript"
+          <form onSubmit={handleSubmit(onSubmit)}>
+            <div>
+              <textarea
+                className="form-control mb-2"
+                rows={8}
+                {...register('customizeScript')}
+              />
+            </div>
+
+            <a
+              className="text-muted"
+              data-bs-toggle="collapse"
+              href="#collapseExampleScript"
+              role="button"
+              aria-expanded="false"
+              aria-controls="collapseExampleScript"
             >
-              {`(function(w,d,s,l,i){
+              <span className="material-symbols-outlined me-1" aria-hidden="true">navigate_next</span>
+              Example for Google Tag Manager
+            </a>
+            <div className="collapse" id="collapseExampleScript">
+              <PrismAsyncLight
+                style={oneDark}
+                language="javascript"
+              >
+                {`(function(w,d,s,l,i){
 w[l]=w[l]||[];
 w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});
 var f=d.getElementsByTagName(s)[0],
@@ -77,10 +92,11 @@ var f=d.getElementsByTagName(s)[0],
 j.async=true;
 j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
 })(window,document,'script','dataLayer','GTM-XXXXXX');`}
-            </PrismAsyncLight>
-          </div>
+              </PrismAsyncLight>
+            </div>
 
-          <AdminUpdateButtonRow onClick={onClickSubmit} disabled={adminCustomizeContainer.state.retrieveError != null} />
+            <AdminUpdateButtonRow type="submit" disabled={adminCustomizeContainer.state.retrieveError != null} />
+          </form>
         </div>
       </div>
     </React.Fragment>

+ 28 - 15
apps/app/src/client/components/Admin/Customize/CustomizeTitle.tsx

@@ -1,7 +1,8 @@
 import type { FC } from 'react';
-import React, { useState } from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
 import { Card, CardBody } from 'reactstrap';
 
 import { apiv3Put } from '~/client/util/apiv3-client';
@@ -16,19 +17,30 @@ export const CustomizeTitle: FC = () => {
 
   const customTitleTemplate = useCustomTitleTemplate();
 
-  const [currentCustomizeTitle, setCrrentCustomizeTitle] = useState(customTitleTemplate ?? '');
+  const {
+    register,
+    handleSubmit,
+    reset,
+  } = useForm();
 
-  const onClickSubmit = async() => {
+  // Sync form with store data
+  useEffect(() => {
+    reset({
+      customizeTitle: customTitleTemplate ?? '',
+    });
+  }, [customTitleTemplate, reset]);
+
+  const onSubmit = useCallback(async(data) => {
     try {
       await apiv3Put('/customize-setting/customize-title', {
-        customizeTitle: currentCustomizeTitle,
+        customizeTitle: data.customizeTitle,
       });
       toastSuccess(t('toaster.update_successed', { target: t('admin:customize_settings.custom_title'), ns: 'commons' }));
     }
     catch (err) {
       toastError(err);
     }
-  };
+  }, [t]);
 
   return (
     <React.Fragment>
@@ -64,16 +76,17 @@ export const CustomizeTitle: FC = () => {
           <br />
           Default Output Example: <code className="xml">&lt;title&gt;Page name - My GROWI&lt;&#047;title&gt;</code>
         </div>
-        <div className="col-12">
-          <input
-            className="form-control"
-            value={currentCustomizeTitle}
-            onChange={(e) => { setCrrentCustomizeTitle(e.target.value) }}
-          />
-        </div>
-        <div className="col-12">
-          <AdminUpdateButtonRow onClick={onClickSubmit} disabled={false} />
-        </div>
+        <form onSubmit={handleSubmit(onSubmit)}>
+          <div className="col-12">
+            <input
+              className="form-control"
+              {...register('customizeTitle')}
+            />
+          </div>
+          <div className="col-12">
+            <AdminUpdateButtonRow type="submit" disabled={false} />
+          </div>
+        </form>
       </div>
     </React.Fragment>
   );

+ 208 - 204
apps/app/src/client/components/Admin/ImportData/ImportDataPageContents.jsx

@@ -2,6 +2,7 @@ import React, { useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
 import PropTypes from 'prop-types';
+import { useForm } from 'react-hook-form';
 
 import AdminImportContainer from '~/client/services/AdminImportContainer';
 import { toastError } from '~/client/util/toastr';
@@ -14,233 +15,236 @@ import GrowiArchiveSection from './GrowiArchiveSection';
 
 const logger = loggerFactory('growi:importer');
 
-class ImportDataPageContents extends React.Component {
-
-  render() {
-    const { t, adminImportContainer } = this.props;
-
-    return (
-      <div data-testid="admin-import-data">
-        <GrowiArchiveSection />
-
-        <form
-          className="mt-5"
-          id="importerSettingFormEsa"
-          role="form"
-        >
-          <fieldset>
-            <h2 className="admin-setting-header">{t('importer_management.import_from', { from: 'esa.io' })}</h2>
-            <table className="table table-bordered table-mapping">
-              <thead>
-                <tr>
-                  <th width="45%">esa.io</th>
-                  <th width="10%"></th>
-                  <th>GROWI</th>
-                </tr>
-              </thead>
-              <tbody>
-                <tr>
-                  <th>{t('importer_management.article')}</th>
-                  <th><span className="material-symbols-outlined text-success">arrow_circle_right</span></th>
-                  <th>{t('importer_management.page')}</th>
-                </tr>
-                <tr>
-                  <th>{t('importer_management.category')}</th>
-                  <th><span className="material-symbols-outlined text-success">arrow_circle_right</span></th>
-                  <th>{t('importer_management.page_path')}</th>
-                </tr>
-                <tr>
-                  <th>{t('User')}</th>
-                  <th></th>
-                  <th>(TBD)</th>
-                </tr>
-              </tbody>
-            </table>
-
-            <div className="card custom-card bg-body-tertiary mb-0 small">
-              <ul>
-                <li>{t('importer_management.page_skip')}</li>
-              </ul>
-            </div>
-
-            <div className="row mt-4">
-              <input type="password" name="dummypass" style={{ display: 'none', top: '-100px', left: '-100px' }} />
-            </div>
+const ImportDataPageContents = ({ t, adminImportContainer }) => {
+  const { register: registerEsa, reset: resetEsa } = useForm();
+  const { register: registerQiita, reset: resetQiita } = useForm();
 
-            <div className="row">
-              <label htmlFor="settingForm[importer:esa:team_name]" className="text-start text-md-end col-md-3 col-form-label">
-                {t('importer_management.esa_settings.team_name')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="esaTeamName"
-                  value={adminImportContainer.state.esaTeamName || ''}
-                  onChange={adminImportContainer.handleInputValue}
-                />
-              </div>
+  useEffect(() => {
+    resetEsa({
+      esaTeamName: adminImportContainer.state.esaTeamName || '',
+      esaAccessToken: adminImportContainer.state.esaAccessToken || '',
+    });
+  }, [resetEsa, adminImportContainer.state.esaTeamName, adminImportContainer.state.esaAccessToken]);
 
+  useEffect(() => {
+    resetQiita({
+      qiitaTeamName: adminImportContainer.state.qiitaTeamName || '',
+      qiitaAccessToken: adminImportContainer.state.qiitaAccessToken || '',
+    });
+  }, [resetQiita, adminImportContainer.state.qiitaTeamName, adminImportContainer.state.qiitaAccessToken]);
+
+  return (
+    <div data-testid="admin-import-data">
+      <GrowiArchiveSection />
+
+      <form
+        className="mt-5"
+        id="importerSettingFormEsa"
+        role="form"
+      >
+        <fieldset>
+          <h2 className="admin-setting-header">{t('importer_management.import_from', { from: 'esa.io' })}</h2>
+          <table className="table table-bordered table-mapping">
+            <thead>
+              <tr>
+                <th width="45%">esa.io</th>
+                <th width="10%"></th>
+                <th>GROWI</th>
+              </tr>
+            </thead>
+            <tbody>
+              <tr>
+                <th>{t('importer_management.article')}</th>
+                <th><span className="material-symbols-outlined text-success">arrow_circle_right</span></th>
+                <th>{t('importer_management.page')}</th>
+              </tr>
+              <tr>
+                <th>{t('importer_management.category')}</th>
+                <th><span className="material-symbols-outlined text-success">arrow_circle_right</span></th>
+                <th>{t('importer_management.page_path')}</th>
+              </tr>
+              <tr>
+                <th>{t('User')}</th>
+                <th></th>
+                <th>(TBD)</th>
+              </tr>
+            </tbody>
+          </table>
+
+          <div className="card custom-card bg-body-tertiary mb-0 small">
+            <ul>
+              <li>{t('importer_management.page_skip')}</li>
+            </ul>
+          </div>
+
+          <div className="row mt-4">
+            <input type="password" name="dummypass" style={{ display: 'none', top: '-100px', left: '-100px' }} />
+          </div>
+
+          <div className="row">
+            <label htmlFor="settingForm[importer:esa:team_name]" className="text-start text-md-end col-md-3 col-form-label">
+              {t('importer_management.esa_settings.team_name')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...registerEsa('esaTeamName')}
+              />
             </div>
 
-            <div className="row mt-3">
-              <label htmlFor="settingForm[importer:esa:access_token]" className="text-start text-md-end col-md-3 col-form-label">
-                {t('importer_management.esa_settings.access_token')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="password"
-                  name="esaAccessToken"
-                  value={adminImportContainer.state.esaAccessToken || ''}
-                  onChange={adminImportContainer.handleInputValue}
-                />
-              </div>
+          </div>
+
+          <div className="row mt-3">
+            <label htmlFor="settingForm[importer:esa:access_token]" className="text-start text-md-end col-md-3 col-form-label">
+              {t('importer_management.esa_settings.access_token')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="password"
+                {...registerEsa('esaAccessToken')}
+              />
             </div>
-
-            <div className="row mt-3">
-              <div className="offset-md-3 col-md-6">
+          </div>
+
+          <div className="row mt-3">
+            <div className="offset-md-3 col-md-6">
+              <input
+                id="testConnectionToEsa"
+                type="button"
+                className="btn btn-primary btn-esa me-3"
+                name="Esa"
+                onClick={adminImportContainer.esaHandleSubmit}
+                value={t('importer_management.import')}
+              />
+              <input type="button" className="btn btn-secondary" onClick={adminImportContainer.esaHandleSubmitUpdate} value={t('Update')} />
+              <span className="offset-0 offset-sm-1">
                 <input
-                  id="testConnectionToEsa"
+                  id="importFromEsa"
                   type="button"
-                  className="btn btn-primary btn-esa me-3"
                   name="Esa"
-                  onClick={adminImportContainer.esaHandleSubmit}
-                  value={t('importer_management.import')}
+                  className="btn btn-secondary btn-esa"
+                  onClick={adminImportContainer.esaHandleSubmitTest}
+                  value={t('importer_management.esa_settings.test_connection')}
                 />
-                <input type="button" className="btn btn-secondary" onClick={adminImportContainer.esaHandleSubmitUpdate} value={t('Update')} />
-                <span className="offset-0 offset-sm-1">
-                  <input
-                    id="importFromEsa"
-                    type="button"
-                    name="Esa"
-                    className="btn btn-secondary btn-esa"
-                    onClick={adminImportContainer.esaHandleSubmitTest}
-                    value={t('importer_management.esa_settings.test_connection')}
-                  />
-                </span>
-
-              </div>
-            </div>
-          </fieldset>
-        </form>
-
-        <form
-          className="mt-5"
-          id="importerSettingFormQiita"
-          role="form"
-        >
-          <fieldset>
-            <h2 className="admin-setting-header">{t('importer_management.import_from', { from: 'Qiita:Team' })}</h2>
-            <table className="table table-bordered table-mapping">
-              <thead>
-                <tr>
-                  <th width="45%">Qiita:Team</th>
-                  <th width="10%"></th>
-                  <th>GROWI</th>
-                </tr>
-              </thead>
-              <tbody>
-                <tr>
-                  <th>{t('importer_management.article')}</th>
-                  <th><span className="material-symbols-outlined">arrow_circle_right</span></th>
-                  <th>{t('importer_management.page')}</th>
-                </tr>
-                <tr>
-                  <th>{t('importer_management.tag')}</th>
-                  <th></th>
-                  <th>-</th>
-                </tr>
-                <tr>
-                  <th>{t('importer_management.Directory_hierarchy_tag')}</th>
-                  <th></th>
-                  <th>(TBD)</th>
-                </tr>
-                <tr>
-                  <th>{t('User')}</th>
-                  <th></th>
-                  <th>(TBD)</th>
-                </tr>
-              </tbody>
-            </table>
-            <div className="card custom-card bg-body-tertiary mb-3 small">
-              <ul>
-                <li>{t('importer_management.page_skip')}</li>
-              </ul>
-            </div>
+              </span>
 
-            <div className="row mt-3">
-              <input type="password" name="dummypass" style={{ display: 'none', top: '-100px', left: '-100px' }} />
             </div>
-            <div className="row mt-3">
-              <label htmlFor="settingForm[importer:qiita:team_name]" className="text-start text-md-end col-md-3 col-form-label">
-                {t('importer_management.qiita_settings.team_name')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="qiitaTeamName"
-                  value={adminImportContainer.state.qiitaTeamName || ''}
-                  onChange={adminImportContainer.handleInputValue}
-                />
-              </div>
+          </div>
+        </fieldset>
+      </form>
+
+      <form
+        className="mt-5"
+        id="importerSettingFormQiita"
+        role="form"
+      >
+        <fieldset>
+          <h2 className="admin-setting-header">{t('importer_management.import_from', { from: 'Qiita:Team' })}</h2>
+          <table className="table table-bordered table-mapping">
+            <thead>
+              <tr>
+                <th width="45%">Qiita:Team</th>
+                <th width="10%"></th>
+                <th>GROWI</th>
+              </tr>
+            </thead>
+            <tbody>
+              <tr>
+                <th>{t('importer_management.article')}</th>
+                <th><span className="material-symbols-outlined">arrow_circle_right</span></th>
+                <th>{t('importer_management.page')}</th>
+              </tr>
+              <tr>
+                <th>{t('importer_management.tag')}</th>
+                <th></th>
+                <th>-</th>
+              </tr>
+              <tr>
+                <th>{t('importer_management.Directory_hierarchy_tag')}</th>
+                <th></th>
+                <th>(TBD)</th>
+              </tr>
+              <tr>
+                <th>{t('User')}</th>
+                <th></th>
+                <th>(TBD)</th>
+              </tr>
+            </tbody>
+          </table>
+          <div className="card custom-card bg-body-tertiary mb-3 small">
+            <ul>
+              <li>{t('importer_management.page_skip')}</li>
+            </ul>
+          </div>
+
+          <div className="row mt-3">
+            <input type="password" name="dummypass" style={{ display: 'none', top: '-100px', left: '-100px' }} />
+          </div>
+          <div className="row mt-3">
+            <label htmlFor="settingForm[importer:qiita:team_name]" className="text-start text-md-end col-md-3 col-form-label">
+              {t('importer_management.qiita_settings.team_name')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...registerQiita('qiitaTeamName')}
+              />
             </div>
-
-            <div className="row mt-3">
-              <label htmlFor="settingForm[importer:qiita:access_token]" className="text-start text-md-end col-md-3 col-form-label">
-                {t('importer_management.qiita_settings.access_token')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="password"
-                  name="qiitaAccessToken"
-                  value={adminImportContainer.state.qiitaAccessToken || ''}
-                  onChange={adminImportContainer.handleInputValue}
-                />
-              </div>
+          </div>
+
+          <div className="row mt-3">
+            <label htmlFor="settingForm[importer:qiita:access_token]" className="text-start text-md-end col-md-3 col-form-label">
+              {t('importer_management.qiita_settings.access_token')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="password"
+                {...registerQiita('qiitaAccessToken')}
+              />
             </div>
-
-
-            <div className="row mt-3">
-              <div className="offset-md-3 col-md-6">
+          </div>
+
+
+          <div className="row mt-3">
+            <div className="offset-md-3 col-md-6">
+              <input
+                id="testConnectionToQiita"
+                type="button"
+                className="btn btn-primary btn-qiita me-3"
+                name="Qiita"
+                onClick={adminImportContainer.qiitaHandleSubmit}
+                value={t('importer_management.import')}
+              />
+              <input type="button" className="btn btn-secondary" onClick={adminImportContainer.qiitaHandleSubmitUpdate} value={t('Update')} />
+              <span className="offset-0 offset-sm-1">
                 <input
-                  id="testConnectionToQiita"
-                  type="button"
-                  className="btn btn-primary btn-qiita me-3"
                   name="Qiita"
-                  onClick={adminImportContainer.qiitaHandleSubmit}
-                  value={t('importer_management.import')}
+                  type="button"
+                  id="importFromQiita"
+                  className="btn btn-secondary btn-qiita"
+                  onClick={adminImportContainer.qiitaHandleSubmitTest}
+                  value={t('importer_management.qiita_settings.test_connection')}
                 />
-                <input type="button" className="btn btn-secondary" onClick={adminImportContainer.qiitaHandleSubmitUpdate} value={t('Update')} />
-                <span className="offset-0 offset-sm-1">
-                  <input
-                    name="Qiita"
-                    type="button"
-                    id="importFromQiita"
-                    className="btn btn-secondary btn-qiita"
-                    onClick={adminImportContainer.qiitaHandleSubmitTest}
-                    value={t('importer_management.qiita_settings.test_connection')}
-                  />
-                </span>
-
-              </div>
-            </div>
+              </span>
 
+            </div>
+          </div>
 
-          </fieldset>
 
+        </fieldset>
 
-        </form>
-      </div>
-    );
-  }
 
-}
+      </form>
+    </div>
+  );
+};
 
 ImportDataPageContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
+  t: PropTypes.func.isRequired,
   adminImportContainer: PropTypes.instanceOf(AdminImportContainer).isRequired,
 };
 

+ 25 - 28
apps/app/src/client/components/Admin/LegacySlackIntegration/SlackConfiguration.jsx

@@ -1,7 +1,8 @@
-import React from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
 import PropTypes from 'prop-types';
+import { useForm } from 'react-hook-form';
 
 import AdminSlackIntegrationLegacyContainer from '~/client/services/AdminSlackIntegrationLegacyContainer';
 import { toastSuccess, toastError } from '~/client/util/toastr';
@@ -12,18 +13,24 @@ import AdminUpdateButtonRow from '../Common/AdminUpdateButtonRow';
 
 const logger = loggerFactory('growi:slackAppConfiguration');
 
-class SlackConfiguration extends React.Component {
+const SlackConfiguration = (props) => {
+  const { t, adminSlackIntegrationLegacyContainer } = props;
+  const { webhookUrl, slackToken, retrieveError } = adminSlackIntegrationLegacyContainer.state;
 
-  constructor(props) {
-    super(props);
+  const { register, handleSubmit, reset } = useForm();
 
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t, adminSlackIntegrationLegacyContainer } = this.props;
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      webhookUrl,
+      slackToken,
+    });
+  }, [reset, webhookUrl, slackToken]);
 
+  const onClickSubmit = useCallback(async(data) => {
     try {
+      await adminSlackIntegrationLegacyContainer.changeWebhookUrl(data.webhookUrl ?? '');
+      await adminSlackIntegrationLegacyContainer.changeSlackToken(data.slackToken ?? '');
       await adminSlackIntegrationLegacyContainer.updateSlackAppConfiguration();
       toastSuccess(t('notification_settings.updated_slackApp'));
     }
@@ -31,12 +38,10 @@ class SlackConfiguration extends React.Component {
       toastError(err);
       logger.error(err);
     }
-  }
-
-  render() {
-    const { t, adminSlackIntegrationLegacyContainer } = this.props;
+  }, [adminSlackIntegrationLegacyContainer, t]);
 
-    return (
+  return (
+    <form onSubmit={handleSubmit(onClickSubmit)}>
       <React.Fragment>
         <div className="row my-3">
           <div className="col-6 text-start">
@@ -70,8 +75,7 @@ class SlackConfiguration extends React.Component {
                 <input
                   className="form-control"
                   type="text"
-                  value={adminSlackIntegrationLegacyContainer.state.webhookUrl || ''}
-                  onChange={e => adminSlackIntegrationLegacyContainer.changeWebhookUrl(e.target.value)}
+                  {...register('webhookUrl')}
                 />
               </div>
             </div>
@@ -122,8 +126,7 @@ class SlackConfiguration extends React.Component {
                   <input
                     className="form-control"
                     type="text"
-                    value={adminSlackIntegrationLegacyContainer.state.slackToken || ''}
-                    onChange={e => adminSlackIntegrationLegacyContainer.changeSlackToken(e.target.value)}
+                    {...register('slackToken')}
                   />
                 </div>
               </div>
@@ -132,10 +135,7 @@ class SlackConfiguration extends React.Component {
           )
         }
 
-        <AdminUpdateButtonRow
-          onClick={this.onClickSubmit}
-          disabled={adminSlackIntegrationLegacyContainer.state.retrieveError != null}
-        />
+        <AdminUpdateButtonRow disabled={retrieveError != null} />
 
         <hr />
 
@@ -164,16 +164,13 @@ class SlackConfiguration extends React.Component {
         </ol>
 
       </React.Fragment>
-    );
-  }
-
-}
-
+    </form>
+  );
+};
 
 SlackConfiguration.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   adminSlackIntegrationLegacyContainer: PropTypes.instanceOf(AdminSlackIntegrationLegacyContainer).isRequired,
-
 };
 
 const SlackConfigurationWrapperFc = (props) => {

+ 17 - 26
apps/app/src/client/components/Admin/MarkdownSetting/WhitelistInput.tsx

@@ -1,41 +1,38 @@
-import { useCallback, useRef, type JSX } from 'react';
+import { useCallback, type JSX } from 'react';
 
 import { useTranslation } from 'next-i18next';
+import type { UseFormRegister, UseFormSetValue } from 'react-hook-form';
 
 import type AdminMarkDownContainer from '~/client/services/AdminMarkDownContainer';
 import { tagNames as recommendedTagNames, attributes as recommendedAttributes } from '~/services/renderer/recommended-whitelist';
 
+type FormValues = {
+  tagWhitelist: string,
+  attrWhitelist: string,
+}
+
 type Props ={
-  adminMarkDownContainer: AdminMarkDownContainer
+  adminMarkDownContainer: AdminMarkDownContainer,
+  register: UseFormRegister<FormValues>,
+  setValue: UseFormSetValue<FormValues>,
 }
 
 export const WhitelistInput = (props: Props): JSX.Element => {
 
   const { t } = useTranslation('admin');
-  const { adminMarkDownContainer } = props;
-
-  const tagNamesRef = useRef<HTMLTextAreaElement>(null);
-  const attrsRef = useRef<HTMLTextAreaElement>(null);
+  const { adminMarkDownContainer, register, setValue } = props;
 
   const clickRecommendTagButtonHandler = useCallback(() => {
-    if (tagNamesRef.current == null) {
-      return;
-    }
-
     const tagWhitelist = recommendedTagNames.join(',');
-    tagNamesRef.current.value = tagWhitelist;
+    setValue('tagWhitelist', tagWhitelist);
     adminMarkDownContainer.setState({ tagWhitelist });
-  }, [adminMarkDownContainer]);
+  }, [adminMarkDownContainer, setValue]);
 
   const clickRecommendAttrButtonHandler = useCallback(() => {
-    if (attrsRef.current == null) {
-      return;
-    }
-
     const attrWhitelist = JSON.stringify(recommendedAttributes);
-    attrsRef.current.value = attrWhitelist;
+    setValue('attrWhitelist', attrWhitelist);
     adminMarkDownContainer.setState({ attrWhitelist });
-  }, [adminMarkDownContainer]);
+  }, [adminMarkDownContainer, setValue]);
 
   return (
     <>
@@ -47,13 +44,10 @@ export const WhitelistInput = (props: Props): JSX.Element => {
           </p>
         </div>
         <textarea
-          ref={tagNamesRef}
           className="form-control xss-list"
-          name="recommendedTags"
           rows={6}
           cols={40}
-          value={adminMarkDownContainer.state.tagWhitelist}
-          onChange={(e) => { adminMarkDownContainer.setState({ tagWhitelist: e.target.value }) }}
+          {...register('tagWhitelist')}
         />
       </div>
       <div className="mt-4">
@@ -64,13 +58,10 @@ export const WhitelistInput = (props: Props): JSX.Element => {
           </p>
         </div>
         <textarea
-          ref={attrsRef}
           className="form-control xss-list"
-          name="recommendedAttrs"
           rows={6}
           cols={40}
-          value={adminMarkDownContainer.state.attrWhitelist}
-          onChange={(e) => { adminMarkDownContainer.setState({ attrWhitelist: e.target.value }) }}
+          {...register('attrWhitelist')}
         />
       </div>
     </>

+ 36 - 30
apps/app/src/client/components/Admin/MarkdownSetting/XssForm.jsx

@@ -1,7 +1,8 @@
-import React from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { useTranslation } from 'next-i18next';
 import PropTypes from 'prop-types';
+import { useForm } from 'react-hook-form';
 
 import AdminMarkDownContainer from '~/client/services/AdminMarkDownContainer';
 import { toastSuccess, toastError } from '~/client/util/toastr';
@@ -16,30 +17,38 @@ import { WhitelistInput } from './WhitelistInput';
 
 const logger = loggerFactory('growi:importer');
 
-class XssForm extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t } = this.props;
-
+const XssForm = (props) => {
+  const { t, adminMarkDownContainer } = props;
+  const {
+    xssOption, tagWhitelist, attrWhitelist, retrieveError,
+  } = adminMarkDownContainer.state;
+
+  const {
+    register, handleSubmit, reset, setValue,
+  } = useForm();
+
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      tagWhitelist,
+      attrWhitelist,
+    });
+  }, [reset, tagWhitelist, attrWhitelist]);
+
+  const onClickSubmit = useCallback(async(data) => {
     try {
-      await this.props.adminMarkDownContainer.updateXssSetting();
+      await adminMarkDownContainer.changeTagWhitelist(data.tagWhitelist ?? '');
+      await adminMarkDownContainer.changeAttrWhitelist(data.attrWhitelist ?? '');
+      await adminMarkDownContainer.updateXssSetting();
       toastSuccess(t('toaster.update_successed', { target: t('markdown_settings.xss_header'), ns: 'commons' }));
     }
     catch (err) {
       toastError(err);
       logger.error(err);
     }
-  }
+  }, [adminMarkDownContainer, t]);
 
-  xssOptions() {
-    const { t, adminMarkDownContainer } = this.props;
-    const { xssOption } = adminMarkDownContainer.state;
+  const xssOptions = useCallback(() => {
 
     const rehypeRecommendedTags = recommendedTagNames.join(',');
     const rehypeRecommendedAttributes = JSON.stringify(recommendedAttributes);
@@ -102,20 +111,19 @@ class XssForm extends React.Component {
               />
               <label className="form-label form-check-label w-100" htmlFor="xssOption2">
                 <p className="fw-bold">{t('markdown_settings.xss_options.custom_whitelist')}</p>
-                <WhitelistInput adminMarkDownContainer={adminMarkDownContainer} />
+                <WhitelistInput adminMarkDownContainer={adminMarkDownContainer} register={register} setValue={setValue} />
               </label>
             </div>
           </div>
         </div>
       </div>
     );
-  }
+  }, [t, adminMarkDownContainer, xssOption, register, setValue]);
 
-  render() {
-    const { t, adminMarkDownContainer } = this.props;
-    const { isEnabledXss } = adminMarkDownContainer.state;
+  const { isEnabledXss } = adminMarkDownContainer.state;
 
-    return (
+  return (
+    <form onSubmit={handleSubmit(onClickSubmit)}>
       <React.Fragment>
         <fieldset className="col-12">
           <div>
@@ -137,16 +145,14 @@ class XssForm extends React.Component {
           </div>
 
           <div className="col-12">
-            {isEnabledXss && this.xssOptions()}
+            {isEnabledXss && xssOptions()}
           </div>
         </fieldset>
-        <AdminUpdateButtonRow onClick={this.onClickSubmit} disabled={adminMarkDownContainer.state.retrieveError != null} />
+        <AdminUpdateButtonRow disabled={retrieveError != null} />
       </React.Fragment>
-    );
-  }
-
-}
-
+    </form>
+  );
+};
 
 XssForm.propTypes = {
   t: PropTypes.func.isRequired, // i18next

+ 39 - 46
apps/app/src/client/components/Admin/Security/GitHubSecuritySettingContents.jsx

@@ -1,9 +1,10 @@
 /* eslint-disable react/no-danger */
-import React from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { pathUtils } from '@growi/core/dist/utils';
 import { useTranslation } from 'next-i18next';
 import PropTypes from 'prop-types';
+import { useForm } from 'react-hook-form';
 import urljoin from 'url-join';
 
 
@@ -14,18 +15,32 @@ import { useSiteUrlWithEmptyValueWarn } from '~/states/global';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
 
-class GitHubSecurityManagementContents extends React.Component {
+const GitHubSecurityManagementContents = (props) => {
+  const {
+    adminGeneralSecurityContainer, adminGitHubSecurityContainer,
+  } = props;
 
-  constructor(props) {
-    super(props);
+  const { t } = useTranslation('admin');
+  const siteUrl = useSiteUrlWithEmptyValueWarn();
+
+  const { isGitHubEnabled } = adminGeneralSecurityContainer.state;
+  const { githubClientId, githubClientSecret, retrieveError } = adminGitHubSecurityContainer.state;
+  const gitHubCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/github/callback');
 
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
+  const { register, handleSubmit, reset } = useForm();
 
-  async onClickSubmit() {
-    const { t, adminGitHubSecurityContainer, adminGeneralSecurityContainer } = this.props;
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      githubClientId,
+      githubClientSecret,
+    });
+  }, [reset, githubClientId, githubClientSecret]);
 
+  const onClickSubmit = useCallback(async(data) => {
     try {
+      await adminGitHubSecurityContainer.changeGitHubClientId(data.githubClientId ?? '');
+      await adminGitHubSecurityContainer.changeGitHubClientSecret(data.githubClientSecret ?? '');
       await adminGitHubSecurityContainer.updateGitHubSetting();
       await adminGeneralSecurityContainer.retrieveSetupStratedies();
       toastSuccess(t('security_settings.OAuth.GitHub.updated_github'));
@@ -33,26 +48,19 @@ class GitHubSecurityManagementContents extends React.Component {
     catch (err) {
       toastError(err);
     }
-  }
-
-  render() {
-    const {
-      t, adminGeneralSecurityContainer, adminGitHubSecurityContainer, siteUrl,
-    } = this.props;
-    const { isGitHubEnabled } = adminGeneralSecurityContainer.state;
-    const gitHubCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/github/callback');
-
-    return (
+  }, [adminGitHubSecurityContainer, adminGeneralSecurityContainer, t]);
 
+  return (
+    <form onSubmit={handleSubmit(onClickSubmit)}>
       <React.Fragment>
 
         <h2 className="alert-anchor border-bottom">
           {t('security_settings.OAuth.GitHub.name')}
         </h2>
 
-        {adminGitHubSecurityContainer.state.retrieveError != null && (
+        {retrieveError != null && (
           <div className="alert alert-danger">
-            <p>{t('Error occurred')} : {adminGitHubSecurityContainer.state.retrieveError}</p>
+            <p>{t('Error occurred')} : {retrieveError}</p>
           </div>
         )}
 
@@ -108,9 +116,7 @@ class GitHubSecurityManagementContents extends React.Component {
                 <input
                   className="form-control"
                   type="text"
-                  name="githubClientId"
-                  value={adminGitHubSecurityContainer.state.githubClientId || ''}
-                  onChange={e => adminGitHubSecurityContainer.changeGitHubClientId(e.target.value)}
+                  {...register('githubClientId')}
                 />
                 <p className="form-text text-muted">
                   <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_GITHUB_CLIENT_ID' }) }} />
@@ -124,9 +130,7 @@ class GitHubSecurityManagementContents extends React.Component {
                 <input
                   className="form-control"
                   type="text"
-                  name="githubClientSecret"
-                  value={adminGitHubSecurityContainer.state.githubClientSecret || ''}
-                  onChange={e => adminGitHubSecurityContainer.changeGitHubClientSecret(e.target.value)}
+                  {...register('githubClientSecret')}
                 />
                 <p className="form-text text-muted">
                   <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_GITHUB_CLIENT_SECRET' }) }} />
@@ -158,9 +162,9 @@ class GitHubSecurityManagementContents extends React.Component {
 
             <div className="row mb-4">
               <div className="offset-3 col-5">
-                <div className="btn btn-primary" disabled={adminGitHubSecurityContainer.state.retrieveError != null} onClick={this.onClickSubmit}>
+                <button type="submit" className="btn btn-primary" disabled={retrieveError != null}>
                   {t('Update')}
-                </div>
+                </button>
               </div>
             </div>
 
@@ -185,32 +189,21 @@ class GitHubSecurityManagementContents extends React.Component {
         </div>
 
       </React.Fragment>
+    </form>
+  );
+};
 
-
-    );
-  }
-
-}
-
-const GitHubSecurityManagementContentsFC = (props) => {
-  const { t } = useTranslation('admin');
-  const siteUrl = useSiteUrlWithEmptyValueWarn();
-  return <GitHubSecurityManagementContents t={t} siteUrl={siteUrl} {...props} />;
+GitHubSecurityManagementContents.propTypes = {
+  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
+  adminGitHubSecurityContainer: PropTypes.instanceOf(AdminGitHubSecurityContainer).isRequired,
 };
 
 /**
  * Wrapper component for using unstated
  */
-const GitHubSecurityManagementContentsWrapper = withUnstatedContainers(GitHubSecurityManagementContentsFC, [
+const GitHubSecurityManagementContentsWrapper = withUnstatedContainers(GitHubSecurityManagementContents, [
   AdminGeneralSecurityContainer,
   AdminGitHubSecurityContainer,
 ]);
 
-GitHubSecurityManagementContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
-  adminGitHubSecurityContainer: PropTypes.instanceOf(AdminGitHubSecurityContainer).isRequired,
-  siteUrl: PropTypes.string.isRequired,
-};
-
 export default GitHubSecurityManagementContentsWrapper;

+ 34 - 48
apps/app/src/client/components/Admin/Security/GoogleSecuritySettingContents.jsx

@@ -1,8 +1,8 @@
-import React from 'react';
+import React, { useCallback, useEffect } from 'react';
 
 import { pathUtils } from '@growi/core/dist/utils';
 import { useTranslation } from 'next-i18next';
-import PropTypes from 'prop-types';
+import { useForm } from 'react-hook-form';
 import urljoin from 'url-join';
 
 import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
@@ -12,18 +12,32 @@ import { useSiteUrlWithEmptyValueWarn } from '~/states/global';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
 
-class GoogleSecurityManagementContents extends React.Component {
+const GoogleSecurityManagementContents = (props) => {
+  const {
+    adminGeneralSecurityContainer, adminGoogleSecurityContainer,
+  } = props;
 
-  constructor(props) {
-    super(props);
+  const { t } = useTranslation('admin');
+  const siteUrl = useSiteUrlWithEmptyValueWarn();
+
+  const { isGoogleEnabled } = adminGeneralSecurityContainer.state;
+  const { googleClientId, googleClientSecret, retrieveError } = adminGoogleSecurityContainer.state;
+  const googleCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/google/callback');
 
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
+  const { register, handleSubmit, reset } = useForm();
 
-  async onClickSubmit() {
-    const { t, adminGoogleSecurityContainer, adminGeneralSecurityContainer } = this.props;
+  // Sync form with container state
+  useEffect(() => {
+    reset({
+      googleClientId,
+      googleClientSecret,
+    });
+  }, [reset, googleClientId, googleClientSecret]);
 
+  const onClickSubmit = useCallback(async(data) => {
     try {
+      await adminGoogleSecurityContainer.changeGoogleClientId(data.googleClientId ?? '');
+      await adminGoogleSecurityContainer.changeGoogleClientSecret(data.googleClientSecret ?? '');
       await adminGoogleSecurityContainer.updateGoogleSetting();
       await adminGeneralSecurityContainer.retrieveSetupStratedies();
       toastSuccess(t('security_settings.OAuth.Google.updated_google'));
@@ -31,26 +45,19 @@ class GoogleSecurityManagementContents extends React.Component {
     catch (err) {
       toastError(err);
     }
-  }
-
-  render() {
-    const {
-      t, adminGeneralSecurityContainer, adminGoogleSecurityContainer, siteUrl,
-    } = this.props;
-    const { isGoogleEnabled } = adminGeneralSecurityContainer.state;
-    const googleCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/google/callback');
-
-    return (
+  }, [adminGoogleSecurityContainer, adminGeneralSecurityContainer, t]);
 
+  return (
+    <form onSubmit={handleSubmit(onClickSubmit)}>
       <React.Fragment>
 
         <h2 className="alert-anchor border-bottom">
           {t('security_settings.OAuth.Google.name')}
         </h2>
 
-        {adminGoogleSecurityContainer.state.retrieveError != null && (
+        {retrieveError != null && (
           <div className="alert alert-danger">
-            <p>{t('Error occurred')} : {adminGoogleSecurityContainer.state.retrieveError}</p>
+            <p>{t('Error occurred')} : {retrieveError}</p>
           </div>
         )}
 
@@ -107,9 +114,7 @@ class GoogleSecurityManagementContents extends React.Component {
                 <input
                   className="form-control"
                   type="text"
-                  name="googleClientId"
-                  value={adminGoogleSecurityContainer.state.googleClientId || ''}
-                  onChange={e => adminGoogleSecurityContainer.changeGoogleClientId(e.target.value)}
+                  {...register('googleClientId')}
                 />
                 <p className="form-text text-muted">
                   <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_GOOGLE_CLIENT_ID' }) }} />
@@ -123,9 +128,7 @@ class GoogleSecurityManagementContents extends React.Component {
                 <input
                   className="form-control"
                   type="password"
-                  name="googleClientSecret"
-                  value={adminGoogleSecurityContainer.state.googleClientSecret || ''}
-                  onChange={e => adminGoogleSecurityContainer.changeGoogleClientSecret(e.target.value)}
+                  {...register('googleClientSecret')}
                 />
                 <p className="form-text text-muted">
                   <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_GOOGLE_CLIENT_SECRET' }) }} />
@@ -157,12 +160,7 @@ class GoogleSecurityManagementContents extends React.Component {
 
             <div className="row mb-4">
               <div className="offset-3 col-5">
-                <button
-                  type="button"
-                  className="btn btn-primary"
-                  disabled={adminGoogleSecurityContainer.state.retrieveError != null}
-                  onClick={this.onClickSubmit}
-                >
+                <button type="submit" className="btn btn-primary" disabled={retrieveError != null}>
                   {t('Update')}
                 </button>
               </div>
@@ -191,28 +189,16 @@ class GoogleSecurityManagementContents extends React.Component {
         </div>
 
       </React.Fragment>
-
-
-    );
-  }
-
-}
-
-const GoogleSecurityManagementContentsFc = (props) => {
-  const { t } = useTranslation('admin');
-  const siteUrl = useSiteUrlWithEmptyValueWarn();
-  return <GoogleSecurityManagementContents t={t} siteUrl={siteUrl} {...props} />;
+    </form>
+  );
 };
 
-
 GoogleSecurityManagementContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
   adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
   adminGoogleSecurityContainer: PropTypes.instanceOf(AdminGoogleSecurityContainer).isRequired,
-  siteUrl: PropTypes.string,
 };
 
-const GoogleSecurityManagementContentsWrapper = withUnstatedContainers(GoogleSecurityManagementContentsFc, [
+const GoogleSecurityManagementContentsWrapper = withUnstatedContainers(GoogleSecurityManagementContents, [
   AdminGeneralSecurityContainer,
   AdminGoogleSecurityContainer,
 ]);

+ 0 - 450
apps/app/src/client/components/Admin/Security/LdapSecuritySettingContents.jsx

@@ -1,450 +0,0 @@
-import React from 'react';
-
-import { useTranslation } from 'next-i18next';
-import PropTypes from 'prop-types';
-
-import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
-import AdminLdapSecurityContainer from '~/client/services/AdminLdapSecurityContainer';
-import { toastSuccess, toastError } from '~/client/util/toastr';
-
-import { withUnstatedContainers } from '../../UnstatedUtils';
-
-import LdapAuthTestModal from './LdapAuthTestModal';
-
-
-class LdapSecuritySettingContents extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      isLdapAuthTestModalShown: false,
-    };
-
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-    this.openLdapAuthTestModal = this.openLdapAuthTestModal.bind(this);
-    this.closeLdapAuthTestModal = this.closeLdapAuthTestModal.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t, adminLdapSecurityContainer, adminGeneralSecurityContainer } = this.props;
-
-    try {
-      await adminLdapSecurityContainer.updateLdapSetting();
-      await adminGeneralSecurityContainer.retrieveSetupStratedies();
-      toastSuccess(t('security_settings.ldap.updated_ldap'));
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  openLdapAuthTestModal() {
-    this.setState({ isLdapAuthTestModalShown: true });
-  }
-
-  closeLdapAuthTestModal() {
-    this.setState({ isLdapAuthTestModalShown: false });
-  }
-
-  render() {
-    const { t, adminGeneralSecurityContainer, adminLdapSecurityContainer } = this.props;
-    const { isLdapEnabled } = adminGeneralSecurityContainer.state;
-
-    return (
-      <React.Fragment>
-
-        <h2 className="alert-anchor border-bottom mb-4">
-          LDAP
-        </h2>
-
-        <div className="row my-4">
-          <div className="col-6 offset-3">
-            <div className="form-check form-switch form-check-success">
-              <input
-                id="isLdapEnabled"
-                className="form-check-input"
-                type="checkbox"
-                checked={isLdapEnabled}
-                onChange={() => { adminGeneralSecurityContainer.switchIsLdapEnabled() }}
-              />
-              <label className="form-label form-check-label" htmlFor="isLdapEnabled">
-                {t('security_settings.ldap.enable_ldap')}
-              </label>
-            </div>
-            {(!adminGeneralSecurityContainer.state.setupStrategies.includes('ldap') && isLdapEnabled)
-              && <div className="badge text-bg-warning">{t('security_settings.setup_is_not_yet_complete')}</div>}
-          </div>
-        </div>
-
-
-        {isLdapEnabled && (
-          <React.Fragment>
-
-            <h3 className="border-bottom mb-4">{t('security_settings.configuration')}</h3>
-
-            <div className="row my-3">
-              <label htmlFor="serverUrl" className="text-start text-md-end col-md-3 col-form-label">
-                Server URL
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="serverUrl"
-                  value={adminLdapSecurityContainer.state.serverUrl || ''}
-                  onChange={e => adminLdapSecurityContainer.changeServerUrl(e.target.value)}
-                />
-                <small>
-                  <p
-                    className="form-text text-muted"
-                    // eslint-disable-next-line react/no-danger
-                    dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.server_url_detail') }}
-                  />
-                  {t('security_settings.example')}: <code>ldaps://ldap.company.com/ou=people,dc=company,dc=com</code>
-                </small>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong>{t('security_settings.ldap.bind_mode')}</strong>
-              </label>
-              <div className="col-md-9">
-                <div className="dropdown">
-                  <button
-                    className="btn btn-outline-secondary dropdown-toggle"
-                    type="button"
-                    id="dropdownMenuButton"
-                    data-bs-toggle="dropdown"
-                    aria-haspopup="true"
-                    aria-expanded="true"
-                  >
-                    {adminLdapSecurityContainer.state.isUserBind
-                      ? <span className="pull-left">{t('security_settings.ldap.bind_user')}</span>
-                      : <span className="pull-left">{t('security_settings.ldap.bind_manager')}</span>}
-                  </button>
-                  <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
-                    <button className="dropdown-item" type="button" onClick={() => { adminLdapSecurityContainer.changeLdapBindMode(true) }}>
-                      {t('security_settings.ldap.bind_user')}
-                    </button>
-                    <button className="dropdown-item" type="button" onClick={() => { adminLdapSecurityContainer.changeLdapBindMode(false) }}>
-                      {t('security_settings.ldap.bind_manager')}
-                    </button>
-                  </div>
-                </div>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong>Bind DN</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="bindDN"
-                  value={adminLdapSecurityContainer.state.ldapBindDN || ''}
-                  onChange={e => adminLdapSecurityContainer.changeBindDN(e.target.value)}
-                />
-                {(adminLdapSecurityContainer.state.isUserBind === true) ? (
-                  <p className="form-text text-muted passport-ldap-userbind">
-                    <small>
-                      {t('security_settings.ldap.bind_DN_user_detail1')}<br />
-                      {/* eslint-disable-next-line react/no-danger */}
-                      <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.bind_DN_user_detail2') }} /><br />
-                      {t('security_settings.example')}1: <code>uid={'{{ username }}'},dc=domain,dc=com</code><br />
-                      {t('security_settings.example')}2: <code>{'{{ username }}'}@domain.com</code>
-                    </small>
-                  </p>
-                )
-                  : (
-                    <p className="form-text text-muted passport-ldap-managerbind">
-                      <small>
-                        {t('security_settings.ldap.bind_DN_manager_detail')}<br />
-                        {t('security_settings.example')}1: <code>uid=admin,dc=domain,dc=com</code><br />
-                        {t('security_settings.example')}2: <code>admin@domain.com</code>
-                      </small>
-                    </p>
-                  )}
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <div htmlFor="bindDNPassword" className="text-start text-md-end col-md-3 col-form-label">
-                <strong>{t('security_settings.ldap.bind_DN_password')}</strong>
-              </div>
-              <div className="col-md-9">
-                {(adminLdapSecurityContainer.state.isUserBind) ? (
-                  <p className="card custom-card passport-ldap-userbind">
-                    <small>
-                      {t('security_settings.ldap.bind_DN_password_user_detail')}
-                    </small>
-                  </p>
-                )
-                  : (
-                    <>
-                      <p className="card custom-card passport-ldap-managerbind">
-                        <small>
-                          {t('security_settings.ldap.bind_DN_password_manager_detail')}
-                        </small>
-                      </p>
-                      <input
-                        className="form-control passport-ldap-managerbind"
-                        type="password"
-                        name="bindDNPassword"
-                        value={adminLdapSecurityContainer.state.ldapBindDNPassword || ''}
-                        onChange={e => adminLdapSecurityContainer.changeBindDNPassword(e.target.value)}
-                      />
-                    </>
-                  )}
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong>{t('security_settings.ldap.search_filter')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="searchFilter"
-                  value={adminLdapSecurityContainer.state.ldapSearchFilter || ''}
-                  onChange={e => adminLdapSecurityContainer.changeSearchFilter(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small>
-                    {t('security_settings.ldap.search_filter_detail1')}<br />
-                    {/* eslint-disable-next-line react/no-danger */}
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.search_filter_detail2') }} /><br />
-                    {/* eslint-disable-next-line react/no-danger */}
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.search_filter_detail3') }} />
-                  </small>
-                </p>
-                <p className="form-text text-muted">
-                  <small>
-                    {t('security_settings.example')}1 - {t('security_settings.ldap.search_filter_example1')}:
-                    <code>(|(uid={'{{username}}'})(mail={'{{username}}'}))</code><br />
-                    {t('security_settings.example')}2 - {t('security_settings.ldap.search_filter_example2')}:
-                    <code>(sAMAccountName={'{{username}}'})</code>
-                  </small>
-                </p>
-              </div>
-            </div>
-
-            <h3 className="alert-anchor border-bottom mb-4">
-              Attribute Mapping ({t('optional')})
-            </h3>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong htmlFor="attrMapUsername">{t('username')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  placeholder="Default: uid"
-                  name="attrMapUsername"
-                  value={adminLdapSecurityContainer.state.ldapAttrMapUsername || ''}
-                  onChange={e => adminLdapSecurityContainer.changeAttrMapUsername(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  {/* eslint-disable-next-line react/no-danger */}
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.username_detail') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <div className="offset-md-3 col-md-9">
-                <div className="form-check form-check-success">
-                  <input
-                    type="checkbox"
-                    className="form-check-input"
-                    id="isSameUsernameTreatedAsIdenticalUser"
-                    checked={adminLdapSecurityContainer.state.isSameUsernameTreatedAsIdenticalUser}
-                    onChange={() => { adminLdapSecurityContainer.switchIsSameUsernameTreatedAsIdenticalUser() }}
-                  />
-                  <label
-                    className="form-check-label"
-                    htmlFor="isSameUsernameTreatedAsIdenticalUser"
-                    // eslint-disable-next-line react/no-danger
-                    dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical') }}
-                  />
-                </div>
-                <p className="form-text text-muted">
-                  {/* eslint-disable-next-line react/no-danger */}
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical_warn') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong htmlFor="attrMapMail">{t('Email')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  placeholder="Default: mail"
-                  name="attrMapMail"
-                  value={adminLdapSecurityContainer.state.ldapAttrMapMail || ''}
-                  onChange={e => adminLdapSecurityContainer.changeAttrMapMail(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small>
-                    {t('security_settings.ldap.mail_detail')}
-                  </small>
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong htmlFor="attrMapName">{t('Name')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="attrMapName"
-                  value={adminLdapSecurityContainer.state.ldapAttrMapName || ''}
-                  onChange={e => adminLdapSecurityContainer.changeAttrMapName(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small>
-                    {t('security_settings.ldap.name_detail')}
-                  </small>
-                </p>
-              </div>
-            </div>
-
-
-            <h3 className="alert-anchor border-bottom mb-4">
-              {t('security_settings.ldap.group_search_filter')} ({t('optional')})
-            </h3>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong htmlFor="groupSearchBase">{t('security_settings.ldap.group_search_base_DN')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="groupSearchBase"
-                  value={adminLdapSecurityContainer.state.ldapGroupSearchBase || ''}
-                  onChange={e => adminLdapSecurityContainer.changeGroupSearchBase(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small>
-                    {/* eslint-disable-next-line react/no-danger */}
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_base_DN_detail') }} /><br />
-                    {t('security_settings.example')}: <code>ou=groups,dc=domain,dc=com</code>
-                  </small>
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong htmlFor="groupSearchFilter">{t('security_settings.ldap.group_search_filter')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="groupSearchFilter"
-                  value={adminLdapSecurityContainer.state.ldapGroupSearchFilter || ''}
-                  onChange={e => adminLdapSecurityContainer.changeGroupSearchFilter(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small>
-                    {/* eslint-disable react/no-danger */}
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail1') }} /><br />
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail2') }} /><br />
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail3') }} />
-                    {/* eslint-enable react/no-danger */}
-                  </small>
-                </p>
-                <p className="form-text text-muted">
-                  <small>
-                    {t('security_settings.example')}:
-                    {/* eslint-disable-next-line react/no-danger */}
-                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail4') }} />
-                  </small>
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">
-                <strong htmlFor="groupDnProperty">{t('security_settings.ldap.group_search_user_DN_property')}</strong>
-              </label>
-              <div className="col-md-9">
-                <input
-                  className="form-control"
-                  type="text"
-                  placeholder="Default: uid"
-                  name="groupDnProperty"
-                  value={adminLdapSecurityContainer.state.ldapGroupDnProperty || ''}
-                  onChange={e => adminLdapSecurityContainer.changeGroupDnProperty(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  {/* eslint-disable-next-line react/no-danger */}
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_user_DN_property_detail') }} />
-                </p>
-              </div>
-            </div>
-            <div className="row my-3">
-              <div className="offset-3 col-5">
-                <button
-                  type="button"
-                  className="btn btn-primary"
-                  disabled={adminLdapSecurityContainer.state.retrieveError != null}
-                  onClick={this.onClickSubmit}
-                >
-                  {t('Update')}
-                </button>
-                <button
-                  type="button"
-                  className="btn btn-outline-secondary ms-2"
-                  onClick={this.openLdapAuthTestModal}
-                >{t('security_settings.ldap.test_config')}
-                </button>
-              </div>
-            </div>
-
-          </React.Fragment>
-        )}
-
-
-        <LdapAuthTestModal isOpen={this.state.isLdapAuthTestModalShown} onClose={this.closeLdapAuthTestModal} />
-
-      </React.Fragment>
-    );
-  }
-
-}
-
-LdapSecuritySettingContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
-  adminLdapSecurityContainer: PropTypes.instanceOf(AdminLdapSecurityContainer).isRequired,
-};
-
-const LdapSecuritySettingContentsWrapperFC = (props) => {
-  const { t } = useTranslation('admin');
-  return <LdapSecuritySettingContents t={t} {...props} />;
-};
-
-const LdapSecuritySettingContentsWrapper = withUnstatedContainers(LdapSecuritySettingContentsWrapperFC, [
-  AdminGeneralSecurityContainer,
-  AdminLdapSecurityContainer,
-]);
-
-export default LdapSecuritySettingContentsWrapper;

+ 446 - 0
apps/app/src/client/components/Admin/Security/LdapSecuritySettingContents.tsx

@@ -0,0 +1,446 @@
+import React, {
+  useState, useEffect, useCallback,
+} from 'react';
+
+import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
+
+import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+import AdminLdapSecurityContainer from '~/client/services/AdminLdapSecurityContainer';
+import { toastSuccess, toastError } from '~/client/util/toastr';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+
+import LdapAuthTestModal from './LdapAuthTestModal';
+
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  adminLdapSecurityContainer: AdminLdapSecurityContainer;
+};
+
+const LdapSecuritySettingContents = (props: Props) => {
+  const { adminGeneralSecurityContainer, adminLdapSecurityContainer } = props;
+
+  const { t } = useTranslation('admin');
+
+  const { isLdapEnabled } = adminGeneralSecurityContainer.state;
+  const {
+    serverUrl, ldapBindDN, ldapBindDNPassword, ldapSearchFilter,
+    ldapAttrMapUsername, ldapAttrMapMail, ldapAttrMapName,
+    ldapGroupSearchBase, ldapGroupSearchFilter, ldapGroupDnProperty,
+  } = adminLdapSecurityContainer.state;
+
+  const [isLdapAuthTestModalShown, setIsLdapAuthTestModalShown] = useState(false);
+
+  const { register, handleSubmit, reset } = useForm();
+
+  useEffect(() => {
+    reset({
+      serverUrl,
+      ldapBindDN,
+      ldapBindDNPassword,
+      ldapSearchFilter,
+      ldapAttrMapUsername,
+      ldapAttrMapMail,
+      ldapAttrMapName,
+      ldapGroupSearchBase,
+      ldapGroupSearchFilter,
+      ldapGroupDnProperty,
+    });
+  }, [
+    reset, serverUrl, ldapBindDN, ldapBindDNPassword, ldapSearchFilter,
+    ldapAttrMapUsername, ldapAttrMapMail, ldapAttrMapName,
+    ldapGroupSearchBase, ldapGroupSearchFilter, ldapGroupDnProperty,
+  ]);
+
+  const onSubmit = useCallback(async(data) => {
+    try {
+      await adminLdapSecurityContainer.changeServerUrl(data.serverUrl);
+      await adminLdapSecurityContainer.changeBindDN(data.ldapBindDN);
+      await adminLdapSecurityContainer.changeBindDNPassword(data.ldapBindDNPassword);
+      await adminLdapSecurityContainer.changeSearchFilter(data.ldapSearchFilter);
+      await adminLdapSecurityContainer.changeAttrMapUsername(data.ldapAttrMapUsername);
+      await adminLdapSecurityContainer.changeAttrMapMail(data.ldapAttrMapMail);
+      await adminLdapSecurityContainer.changeAttrMapName(data.ldapAttrMapName);
+      await adminLdapSecurityContainer.changeGroupSearchBase(data.ldapGroupSearchBase);
+      await adminLdapSecurityContainer.changeGroupSearchFilter(data.ldapGroupSearchFilter);
+      await adminLdapSecurityContainer.changeGroupDnProperty(data.ldapGroupDnProperty);
+      await adminLdapSecurityContainer.updateLdapSetting();
+      await adminGeneralSecurityContainer.retrieveSetupStratedies();
+      toastSuccess(t('security_settings.ldap.updated_ldap'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [t, adminLdapSecurityContainer, adminGeneralSecurityContainer]);
+
+  const openLdapAuthTestModal = useCallback(() => {
+    setIsLdapAuthTestModalShown(true);
+  }, []);
+
+  const closeLdapAuthTestModal = useCallback(() => {
+    setIsLdapAuthTestModalShown(false);
+  }, []);
+
+  return (
+    <React.Fragment>
+
+      <h2 className="alert-anchor border-bottom mb-4">
+        LDAP
+      </h2>
+
+      <div className="row my-4">
+        <div className="col-6 offset-3">
+          <div className="form-check form-switch form-check-success">
+            <input
+              id="isLdapEnabled"
+              className="form-check-input"
+              type="checkbox"
+              checked={isLdapEnabled}
+              onChange={() => { adminGeneralSecurityContainer.switchIsLdapEnabled() }}
+            />
+            <label className="form-label form-check-label" htmlFor="isLdapEnabled">
+              {t('security_settings.ldap.enable_ldap')}
+            </label>
+          </div>
+          {(!adminGeneralSecurityContainer.state.setupStrategies.includes('ldap') && isLdapEnabled)
+              && <div className="badge text-bg-warning">{t('security_settings.setup_is_not_yet_complete')}</div>}
+        </div>
+      </div>
+
+
+      {isLdapEnabled && (
+        <form onSubmit={handleSubmit(onSubmit)}>
+
+          <h3 className="border-bottom mb-4">{t('security_settings.configuration')}</h3>
+
+          <div className="row my-3">
+            <label htmlFor="serverUrl" className="text-start text-md-end col-md-3 col-form-label">
+              Server URL
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                {...register('serverUrl')}
+              />
+              <small>
+                <p
+                  className="form-text text-muted"
+                  // eslint-disable-next-line react/no-danger
+                  dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.server_url_detail') }}
+                />
+                {t('security_settings.example')}: <code>ldaps://ldap.company.com/ou=people,dc=company,dc=com</code>
+              </small>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label">
+              <strong>{t('security_settings.ldap.bind_mode')}</strong>
+            </label>
+            <div className="col-md-9">
+              <div className="dropdown">
+                <button
+                  className="btn btn-outline-secondary dropdown-toggle"
+                  type="button"
+                  id="dropdownMenuButton"
+                  data-bs-toggle="dropdown"
+                  aria-haspopup="true"
+                  aria-expanded="true"
+                >
+                  {adminLdapSecurityContainer.state.isUserBind
+                    ? <span className="pull-left">{t('security_settings.ldap.bind_user')}</span>
+                    : <span className="pull-left">{t('security_settings.ldap.bind_manager')}</span>}
+                </button>
+                <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
+                  <button className="dropdown-item" type="button" onClick={() => { adminLdapSecurityContainer.changeLdapBindMode(true) }}>
+                    {t('security_settings.ldap.bind_user')}
+                  </button>
+                  <button className="dropdown-item" type="button" onClick={() => { adminLdapSecurityContainer.changeLdapBindMode(false) }}>
+                    {t('security_settings.ldap.bind_manager')}
+                  </button>
+                </div>
+              </div>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label">
+              <strong>Bind DN</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                {...register('ldapBindDN')}
+              />
+              {(adminLdapSecurityContainer.state.isUserBind === true) ? (
+                <p className="form-text text-muted">
+                  <small>
+                    {t('security_settings.ldap.bind_DN_user_detail1')}<br />
+                    {/* eslint-disable-next-line react/no-danger */}
+                    <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.bind_DN_user_detail2') }} /><br />
+                    {t('security_settings.example')}1: <code>uid={'{{ username }}'},dc=domain,dc=com</code><br />
+                    {t('security_settings.example')}2: <code>{'{{ username }}'}@domain.com</code>
+                  </small>
+                </p>
+              )
+                : (
+                  <p className="form-text text-muted">
+                    <small>
+                      {t('security_settings.ldap.bind_DN_manager_detail')}<br />
+                      {t('security_settings.example')}1: <code>uid=admin,dc=domain,dc=com</code><br />
+                      {t('security_settings.example')}2: <code>admin@domain.com</code>
+                    </small>
+                  </p>
+                )}
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="text-start text-md-end col-md-3 col-form-label" htmlFor="bindDNPassword">
+              <strong>{t('security_settings.ldap.bind_DN_password')}</strong>
+            </label>
+            <div className="col-md-9">
+              {(adminLdapSecurityContainer.state.isUserBind) ? (
+                <p className="card custom-card">
+                  <small>
+                    {t('security_settings.ldap.bind_DN_password_user_detail')}
+                  </small>
+                </p>
+              )
+                : (
+                  <>
+                    <input
+                      className="form-control"
+                      type="password"
+                      {...register('ldapBindDNPassword')}
+                    />
+                    <p className="form-text text-muted">
+                      <small>{t('security_settings.ldap.bind_DN_password_manager_detail')}</small>
+                    </p>
+                  </>
+                )}
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label">
+              <strong>{t('security_settings.ldap.search_filter')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                {...register('ldapSearchFilter')}
+              />
+              <p className="form-text text-muted">
+                <small>
+                  {t('security_settings.ldap.search_filter_detail1')}<br />
+                  {/* eslint-disable-next-line react/no-danger */}
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.search_filter_detail2') }} /><br />
+                  {/* eslint-disable-next-line react/no-danger */}
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.search_filter_detail3') }} />
+                </small>
+              </p>
+              <p className="form-text text-muted">
+                <small>
+                  {t('security_settings.example')}1 - {t('security_settings.ldap.search_filter_example1')}:
+                  <code>(|(uid={'{{username}}'})(mail={'{{username}}'}))</code><br />
+                  {t('security_settings.example')}2 - {t('security_settings.ldap.search_filter_example2')}:
+                  <code>(sAMAccountName={'{{username}}'})</code>
+                </small>
+              </p>
+            </div>
+          </div>
+
+          <h3 className="alert-anchor border-bottom mb-4">
+            Attribute Mapping ({t('optional')})
+          </h3>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label" htmlFor="attrMapUsername">
+              <strong>{t('username')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                placeholder="Default: uid"
+                {...register('ldapAttrMapUsername')}
+              />
+              <p className="form-text text-muted">
+                {/* eslint-disable-next-line react/no-danger */}
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.username_detail') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <div className="offset-md-3 col-md-9">
+              <div className="form-check form-check-success">
+                <input
+                  type="checkbox"
+                  className="form-check-input"
+                  id="isSameUsernameTreatedAsIdenticalUser"
+                  checked={adminLdapSecurityContainer.state.isSameUsernameTreatedAsIdenticalUser}
+                  onChange={() => { adminLdapSecurityContainer.switchIsSameUsernameTreatedAsIdenticalUser() }}
+                />
+                <label
+                  className="form-check-label"
+                  htmlFor="isSameUsernameTreatedAsIdenticalUser"
+                  // eslint-disable-next-line react/no-danger
+                  dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical') }}
+                />
+              </div>
+              <p className="form-text text-muted">
+                {/* eslint-disable-next-line react/no-danger */}
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical_warn') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label" htmlFor="attrMapMail">
+              <strong>{t('Email')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                placeholder="Default: mail"
+                {...register('ldapAttrMapMail')}
+              />
+              <p className="form-text text-muted">
+                <small>
+                  {t('security_settings.ldap.mail_detail')}
+                </small>
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label" htmlFor="attrMapName">
+              <strong>{t('Name')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                {...register('ldapAttrMapName')}
+              />
+              <p className="form-text text-muted">
+                <small>
+                  {t('security_settings.ldap.name_detail')}
+                </small>
+              </p>
+            </div>
+          </div>
+
+
+          <h3 className="alert-anchor border-bottom mb-4">
+            {t('security_settings.ldap.group_search_filter')} ({t('optional')})
+          </h3>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label" htmlFor="groupSearchBase">
+              <strong>{t('security_settings.ldap.group_search_base_DN')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                {...register('ldapGroupSearchBase')}
+              />
+              <p className="form-text text-muted">
+                <small>
+                  {/* eslint-disable-next-line react/no-danger */}
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_base_DN_detail') }} /><br />
+                  {t('security_settings.example')}: <code>ou=groups,dc=domain,dc=com</code>
+                </small>
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label" htmlFor="groupSearchFilter">
+              <strong>{t('security_settings.ldap.group_search_filter')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                {...register('ldapGroupSearchFilter')}
+              />
+              <p className="form-text text-muted">
+                <small>
+                  {/* eslint-disable react/no-danger */}
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail1') }} /><br />
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail2') }} /><br />
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail3') }} />
+                  {/* eslint-enable react/no-danger */}
+                </small>
+              </p>
+              <p className="form-text text-muted">
+                <small>
+                  {t('security_settings.example')}:
+                  {/* eslint-disable-next-line react/no-danger */}
+                  <span dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_filter_detail4') }} />
+                </small>
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label" htmlFor="groupDnProperty">
+              <strong>{t('security_settings.ldap.group_search_user_DN_property')}</strong>
+            </label>
+            <div className="col-md-9">
+              <input
+                className="form-control"
+                type="text"
+                placeholder="Default: uid"
+                {...register('ldapGroupDnProperty')}
+              />
+              <p className="form-text text-muted">
+                {/* eslint-disable-next-line react/no-danger */}
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.ldap.group_search_user_DN_property_detail') }} />
+              </p>
+            </div>
+          </div>
+          <div className="row my-3">
+            <div className="offset-3 col-5">
+              <button
+                type="submit"
+                className="btn btn-primary"
+                disabled={adminLdapSecurityContainer.state.retrieveError != null}
+              >
+                {t('Update')}
+              </button>
+              <button
+                type="button"
+                className="btn btn-outline-secondary ms-2"
+                onClick={openLdapAuthTestModal}
+              >{t('security_settings.ldap.test_config')}
+              </button>
+            </div>
+          </div>
+
+        </form>
+      )}
+
+
+      <LdapAuthTestModal isOpen={isLdapAuthTestModalShown} onClose={closeLdapAuthTestModal} />
+
+    </React.Fragment>
+  );
+};
+
+const LdapSecuritySettingContentsWrapper = withUnstatedContainers(LdapSecuritySettingContents, [
+  AdminGeneralSecurityContainer,
+  AdminLdapSecurityContainer,
+]);
+
+export default LdapSecuritySettingContentsWrapper;

+ 0 - 261
apps/app/src/client/components/Admin/Security/LocalSecuritySettingContents.jsx

@@ -1,261 +0,0 @@
-import React from 'react';
-
-import { useAtomValue } from 'jotai';
-import { useTranslation } from 'next-i18next';
-import Link from 'next/link';
-import PropTypes from 'prop-types';
-
-import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
-import AdminLocalSecurityContainer from '~/client/services/AdminLocalSecurityContainer';
-import { toastSuccess, toastError } from '~/client/util/toastr';
-import { isMailerSetupAtom } from '~/states/server-configurations';
-
-import { withUnstatedContainers } from '../../UnstatedUtils';
-
-class LocalSecuritySettingContents extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t, adminGeneralSecurityContainer, adminLocalSecurityContainer } = this.props;
-    try {
-      await adminLocalSecurityContainer.updateLocalSecuritySetting();
-      await adminGeneralSecurityContainer.retrieveSetupStratedies();
-      toastSuccess(t('security_settings.updated_general_security_setting'));
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  render() {
-    const {
-      t,
-      adminGeneralSecurityContainer,
-      adminLocalSecurityContainer,
-      isMailerSetup,
-    } = this.props;
-    const { registrationMode, isPasswordResetEnabled, isEmailAuthenticationEnabled } = adminLocalSecurityContainer.state;
-    const { isLocalEnabled } = adminGeneralSecurityContainer.state;
-
-    return (
-      <>
-        {adminLocalSecurityContainer.state.retrieveError != null && (
-          <div className="alert alert-danger">
-            <p>
-              {t('Error occurred')} : {adminLocalSecurityContainer.state.retrieveError}
-            </p>
-          </div>
-        )}
-        <h2 className="alert-anchor border-bottom">{t('security_settings.Local.name')}</h2>
-
-        {adminLocalSecurityContainer.state.useOnlyEnvVars && (
-          <p
-            className="alert alert-info"
-            // eslint-disable-next-line max-len
-            dangerouslySetInnerHTML={{
-              __html: t('security_settings.Local.note for the only env option', { env: 'LOCAL_STRATEGY_USES_ONLY_ENV_VARS_FOR_SOME_OPTIONS' }),
-            }}
-          />
-        )}
-
-        <div className="row mt-4 mb-5">
-          <div className="col-6 offset-3">
-            <div className="form-check form-switch form-check-success">
-              <input
-                type="checkbox"
-                className="form-check-input"
-                id="isLocalEnabled"
-                checked={isLocalEnabled}
-                onChange={() => adminGeneralSecurityContainer.switchIsLocalEnabled()}
-                disabled={adminLocalSecurityContainer.state.useOnlyEnvVars}
-              />
-              <label className="form-label form-check-label" htmlFor="isLocalEnabled">
-                {t('security_settings.Local.enable_local')}
-              </label>
-            </div>
-            {!adminGeneralSecurityContainer.state.setupStrategies.includes('local') && isLocalEnabled && (
-              <div className="badge bg-warning text-dark">{t('security_settings.setup_is_not_yet_complete')}</div>
-            )}
-          </div>
-        </div>
-
-        {isLocalEnabled && (
-          <>
-            <h3 className="border-bottom">{t('security_settings.configuration')}</h3>
-
-            <div className="row">
-              <div className="col-12 col-md-4 text-start text-md-end py-2">
-                <strong>{t('security_settings.register_limitation')}</strong>
-              </div>
-              <div className="col-12 col-md-8">
-                <div className="dropdown">
-                  <button
-                    className="btn btn-outline-secondary dropdown-toggle"
-                    type="button"
-                    id="dropdownMenuButton"
-                    data-bs-toggle="dropdown"
-                    aria-haspopup="true"
-                    aria-expanded="true"
-                  >
-                    {registrationMode === 'Open' && t('security_settings.registration_mode.open')}
-                    {registrationMode === 'Restricted' && t('security_settings.registration_mode.restricted')}
-                    {registrationMode === 'Closed' && t('security_settings.registration_mode.closed')}
-                  </button>
-                  <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
-                    <button
-                      className="dropdown-item"
-                      type="button"
-                      onClick={() => {
-                        adminLocalSecurityContainer.changeRegistrationMode('Open');
-                      }}
-                    >
-                      {t('security_settings.registration_mode.open')}
-                    </button>
-                    <button
-                      className="dropdown-item"
-                      type="button"
-                      onClick={() => {
-                        adminLocalSecurityContainer.changeRegistrationMode('Restricted');
-                      }}
-                    >
-                      {t('security_settings.registration_mode.restricted')}
-                    </button>
-                    <button
-                      className="dropdown-item"
-                      type="button"
-                      onClick={() => {
-                        adminLocalSecurityContainer.changeRegistrationMode('Closed');
-                      }}
-                    >
-                      {t('security_settings.registration_mode.closed')}
-                    </button>
-                  </div>
-                </div>
-                <p className="form-text text-muted small">{t('security_settings.register_limitation_desc')}</p>
-              </div>
-            </div>
-            <div className="row">
-              <div className="col-12 col-md-4 text-start text-md-end">
-                <strong dangerouslySetInnerHTML={{ __html: t('security_settings.The whitelist of registration permission E-mail address') }} />
-              </div>
-              <div className="col-12 col-md-8">
-                <textarea
-                  className="form-control"
-                  type="textarea"
-                  name="registrationWhitelist"
-                  value={adminLocalSecurityContainer.state.registrationWhitelist.join('\n')}
-                  onChange={e => adminLocalSecurityContainer.changeRegistrationWhitelist(e.target.value)}
-                />
-                <p className="form-text text-muted small">
-                  {t('security_settings.restrict_emails')}
-                  <br />
-                  {t('security_settings.for_example')}
-                  <code>@growi.org</code>
-                  {t('security_settings.in_this_case')}
-                  <br />
-                  {t('security_settings.insert_single')}
-                </p>
-              </div>
-            </div>
-
-            <div className="row">
-              <label className="col-12 col-md-4 text-start text-md-end  col-form-label">{t('security_settings.Local.password_reset_by_users')}</label>
-              <div className="col-12 col-md-8">
-                <div className="form-check form-switch form-check-success">
-                  <input
-                    type="checkbox"
-                    className="form-check-input"
-                    id="isPasswordResetEnabled"
-                    checked={isPasswordResetEnabled}
-                    onChange={() => adminLocalSecurityContainer.switchIsPasswordResetEnabled()}
-                  />
-                  <label className="form-label form-check-label" htmlFor="isPasswordResetEnabled">
-                    {t('security_settings.Local.enable_password_reset_by_users')}
-                  </label>
-                </div>
-                {!isMailerSetup && (
-                  <div className="alert alert-warning p-2 my-1 small d-inline-block">
-                    <span>{t('commons:alert.password_reset_please_enable_mailer')}</span>
-                    <Link href="/admin/app#mail-settings">
-                      <span className="material-symbols-outlined">link</span> {t('app_setting.mail_settings')}
-                    </Link>
-                  </div>
-                )}
-                <p className="form-text text-muted small">
-                  {t('security_settings.Local.password_reset_desc')}
-                </p>
-              </div>
-            </div>
-
-            <div className="row">
-              <label className="col-12 col-md-4 text-start text-md-end  col-form-label">{t('security_settings.Local.email_authentication')}</label>
-              <div className="col-12 col-md-8">
-                <div className="form-check form-switch form-check-success">
-                  <input
-                    type="checkbox"
-                    className="form-check-input"
-                    id="isEmailAuthenticationEnabled"
-                    checked={isEmailAuthenticationEnabled}
-                    onChange={() => adminLocalSecurityContainer.switchIsEmailAuthenticationEnabled()}
-                  />
-                  <label className="form-label form-check-label" htmlFor="isEmailAuthenticationEnabled">
-                    {t('security_settings.Local.enable_email_authentication')}
-                  </label>
-                </div>
-                {!isMailerSetup && (
-                  <div className="alert alert-warning p-2 my-1 small d-inline-block">
-                    <span>{t('commons:alert.please_enable_mailer')}</span>
-                    <Link href="/admin/app#mail-settings">
-                      <span className="material-symbols-outlined">link</span> {t('app_setting.mail_settings')}
-                    </Link>
-                  </div>
-                )}
-                <p className="form-text text-muted small">
-                  {t('security_settings.Local.enable_email_authentication_desc')}
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <div className="offset-3 col-6">
-                <button
-                  type="button"
-                  className="btn btn-primary"
-                  disabled={adminLocalSecurityContainer.state.retrieveError != null}
-                  onClick={this.onClickSubmit}
-                >
-                  {t('Update')}
-                </button>
-              </div>
-            </div>
-          </>
-        )}
-      </>
-    );
-  }
-
-}
-
-LocalSecuritySettingContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
-  adminLocalSecurityContainer: PropTypes.instanceOf(AdminLocalSecurityContainer).isRequired,
-};
-
-const LocalSecuritySettingContentsWrapperFC = (props) => {
-  const { t } = useTranslation('admin');
-  const isMailerSetup = useAtomValue(isMailerSetupAtom);
-  return <LocalSecuritySettingContents t={t} {...props} isMailerSetup={isMailerSetup ?? false} />;
-};
-
-const LocalSecuritySettingContentsWrapper = withUnstatedContainers(LocalSecuritySettingContentsWrapperFC, [
-  AdminGeneralSecurityContainer,
-  AdminLocalSecurityContainer,
-]);
-
-export default LocalSecuritySettingContentsWrapper;

+ 249 - 0
apps/app/src/client/components/Admin/Security/LocalSecuritySettingContents.tsx

@@ -0,0 +1,249 @@
+import React, { useCallback, useEffect } from 'react';
+import Link from 'next/link';
+import { useTranslation } from 'next-i18next';
+import { useAtomValue } from 'jotai';
+import { useForm } from 'react-hook-form';
+
+import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+import AdminLocalSecurityContainer from '~/client/services/AdminLocalSecurityContainer';
+import { toastSuccess, toastError } from '~/client/util/toastr';
+import { isMailerSetupAtom } from '~/states/server-configurations';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  adminLocalSecurityContainer: AdminLocalSecurityContainer;
+};
+
+const LocalSecuritySettingContents = (props: Props): JSX.Element => {
+  const {
+    adminGeneralSecurityContainer,
+    adminLocalSecurityContainer,
+  } = props;
+
+  const { t } = useTranslation('admin');
+  const isMailerSetup = useAtomValue(isMailerSetupAtom);
+
+  const { register, handleSubmit, reset } = useForm();
+
+  const { registrationMode, isPasswordResetEnabled, isEmailAuthenticationEnabled } = adminLocalSecurityContainer.state;
+  const { isLocalEnabled } = adminGeneralSecurityContainer.state;
+
+  useEffect(() => {
+    reset({
+      registrationWhitelist: adminLocalSecurityContainer.state.registrationWhitelist.join('\n'),
+    });
+  }, [reset, adminLocalSecurityContainer.state.registrationWhitelist]);
+
+  const onSubmit = useCallback(async(data) => {
+    try {
+      await adminLocalSecurityContainer.changeRegistrationWhitelist(data.registrationWhitelist);
+      await adminLocalSecurityContainer.updateLocalSecuritySetting();
+      await adminGeneralSecurityContainer.retrieveSetupStratedies();
+      toastSuccess(t('security_settings.updated_general_security_setting'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [t, adminGeneralSecurityContainer, adminLocalSecurityContainer]);
+
+  return (
+    <>
+      {adminLocalSecurityContainer.state.retrieveError != null && (
+        <div className="alert alert-danger">
+          <p>
+            {t('Error occurred')} : {adminLocalSecurityContainer.state.retrieveError}
+          </p>
+        </div>
+      )}
+      <h2 className="alert-anchor border-bottom">{t('security_settings.Local.name')}</h2>
+
+      {adminLocalSecurityContainer.state.useOnlyEnvVars && (
+        <p
+          className="alert alert-info"
+          // eslint-disable-next-line max-len
+          dangerouslySetInnerHTML={{
+            __html: t('security_settings.Local.note for the only env option', { env: 'LOCAL_STRATEGY_USES_ONLY_ENV_VARS_FOR_SOME_OPTIONS' }),
+          }}
+        />
+      )}
+
+      <div className="row mt-4 mb-5">
+        <div className="col-6 offset-3">
+          <div className="form-check form-switch form-check-success">
+            <input
+              type="checkbox"
+              className="form-check-input"
+              id="isLocalEnabled"
+              checked={isLocalEnabled}
+              onChange={() => adminGeneralSecurityContainer.switchIsLocalEnabled()}
+              disabled={adminLocalSecurityContainer.state.useOnlyEnvVars}
+            />
+            <label className="form-label form-check-label" htmlFor="isLocalEnabled">
+              {t('security_settings.Local.enable_local')}
+            </label>
+          </div>
+          {!adminGeneralSecurityContainer.state.setupStrategies.includes('local') && isLocalEnabled && (
+            <div className="badge bg-warning text-dark">{t('security_settings.setup_is_not_yet_complete')}</div>
+          )}
+        </div>
+      </div>
+
+      {isLocalEnabled && (
+        <form onSubmit={handleSubmit(onSubmit)}>
+          <h3 className="border-bottom">{t('security_settings.configuration')}</h3>
+
+          <div className="row">
+            <div className="col-12 col-md-4 text-start text-md-end py-2">
+              <strong>{t('security_settings.register_limitation')}</strong>
+            </div>
+            <div className="col-12 col-md-8">
+              <div className="dropdown">
+                <button
+                  className="btn btn-outline-secondary dropdown-toggle"
+                  type="button"
+                  id="dropdownMenuButton"
+                  data-bs-toggle="dropdown"
+                  aria-haspopup="true"
+                  aria-expanded="true"
+                >
+                  {registrationMode === 'Open' && t('security_settings.registration_mode.open')}
+                  {registrationMode === 'Restricted' && t('security_settings.registration_mode.restricted')}
+                  {registrationMode === 'Closed' && t('security_settings.registration_mode.closed')}
+                </button>
+                <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
+                  <button
+                    className="dropdown-item"
+                    type="button"
+                    onClick={() => {
+                      adminLocalSecurityContainer.changeRegistrationMode('Open');
+                    }}
+                  >
+                    {t('security_settings.registration_mode.open')}
+                  </button>
+                  <button
+                    className="dropdown-item"
+                    type="button"
+                    onClick={() => {
+                      adminLocalSecurityContainer.changeRegistrationMode('Restricted');
+                    }}
+                  >
+                    {t('security_settings.registration_mode.restricted')}
+                  </button>
+                  <button
+                    className="dropdown-item"
+                    type="button"
+                    onClick={() => {
+                      adminLocalSecurityContainer.changeRegistrationMode('Closed');
+                    }}
+                  >
+                    {t('security_settings.registration_mode.closed')}
+                  </button>
+                </div>
+              </div>
+              <p className="form-text text-muted small">{t('security_settings.register_limitation_desc')}</p>
+            </div>
+          </div>
+          <div className="row">
+            <div className="col-12 col-md-4 text-start text-md-end">
+              <strong dangerouslySetInnerHTML={{ __html: t('security_settings.The whitelist of registration permission E-mail address') }} />
+            </div>
+            <div className="col-12 col-md-8">
+              <textarea
+                className="form-control"
+                {...register('registrationWhitelist')}
+              />
+              <p className="form-text text-muted small">
+                {t('security_settings.restrict_emails')}
+                <br />
+                {t('security_settings.for_example')}
+                <code>@growi.org</code>
+                {t('security_settings.in_this_case')}
+                <br />
+                {t('security_settings.insert_single')}
+              </p>
+            </div>
+          </div>
+
+          <div className="row">
+            <label className="col-12 col-md-4 text-start text-md-end  col-form-label">{t('security_settings.Local.password_reset_by_users')}</label>
+            <div className="col-12 col-md-8">
+              <div className="form-check form-switch form-check-success">
+                <input
+                  type="checkbox"
+                  className="form-check-input"
+                  id="isPasswordResetEnabled"
+                  checked={isPasswordResetEnabled}
+                  onChange={() => adminLocalSecurityContainer.switchIsPasswordResetEnabled()}
+                />
+                <label className="form-label form-check-label" htmlFor="isPasswordResetEnabled">
+                  {t('security_settings.Local.enable_password_reset_by_users')}
+                </label>
+              </div>
+              {!isMailerSetup && (
+                <div className="alert alert-warning p-2 my-1 small d-inline-block">
+                  <span>{t('commons:alert.password_reset_please_enable_mailer')}</span>
+                  <Link href="/admin/app#mail-settings">
+                    <span className="material-symbols-outlined">link</span> {t('app_setting.mail_settings')}
+                  </Link>
+                </div>
+              )}
+              <p className="form-text text-muted small">
+                {t('security_settings.Local.password_reset_desc')}
+              </p>
+            </div>
+          </div>
+
+          <div className="row">
+            <label className="col-12 col-md-4 text-start text-md-end  col-form-label">{t('security_settings.Local.email_authentication')}</label>
+            <div className="col-12 col-md-8">
+              <div className="form-check form-switch form-check-success">
+                <input
+                  type="checkbox"
+                  className="form-check-input"
+                  id="isEmailAuthenticationEnabled"
+                  checked={isEmailAuthenticationEnabled}
+                  onChange={() => adminLocalSecurityContainer.switchIsEmailAuthenticationEnabled()}
+                />
+                <label className="form-label form-check-label" htmlFor="isEmailAuthenticationEnabled">
+                  {t('security_settings.Local.enable_email_authentication')}
+                </label>
+              </div>
+              {!isMailerSetup && (
+                <div className="alert alert-warning p-2 my-1 small d-inline-block">
+                  <span>{t('commons:alert.please_enable_mailer')}</span>
+                  <Link href="/admin/app#mail-settings">
+                    <span className="material-symbols-outlined">link</span> {t('app_setting.mail_settings')}
+                  </Link>
+                </div>
+              )}
+              <p className="form-text text-muted small">
+                {t('security_settings.Local.enable_email_authentication_desc')}
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <div className="offset-3 col-6">
+              <button
+                type="submit"
+                className="btn btn-primary"
+                disabled={adminLocalSecurityContainer.state.retrieveError != null}
+              >
+                {t('Update')}
+              </button>
+            </div>
+          </div>
+        </form>
+      )}
+    </>
+  );
+};
+
+const LocalSecuritySettingContentsWrapper = withUnstatedContainers(LocalSecuritySettingContents, [
+  AdminGeneralSecurityContainer,
+  AdminLocalSecurityContainer,
+]);
+
+export default LocalSecuritySettingContentsWrapper;

+ 0 - 488
apps/app/src/client/components/Admin/Security/OidcSecuritySettingContents.jsx

@@ -1,488 +0,0 @@
-import React from 'react';
-
-import { pathUtils } from '@growi/core/dist/utils';
-import { useTranslation } from 'next-i18next';
-import PropTypes from 'prop-types';
-import urljoin from 'url-join';
-
-
-import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
-import AdminOidcSecurityContainer from '~/client/services/AdminOidcSecurityContainer';
-import { toastSuccess, toastError } from '~/client/util/toastr';
-import { useSiteUrlWithEmptyValueWarn } from '~/states/global';
-
-import { withUnstatedContainers } from '../../UnstatedUtils';
-
-class OidcSecurityManagementContents extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t, adminOidcSecurityContainer, adminGeneralSecurityContainer } = this.props;
-
-    try {
-      await adminOidcSecurityContainer.updateOidcSetting();
-      await adminGeneralSecurityContainer.retrieveSetupStratedies();
-      toastSuccess(t('security_settings.OAuth.OIDC.updated_oidc'));
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  render() {
-    const {
-      t, adminGeneralSecurityContainer, adminOidcSecurityContainer, siteUrl,
-    } = this.props;
-    const { isOidcEnabled } = adminGeneralSecurityContainer.state;
-    const oidcCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/oidc/callback');
-
-    return (
-
-      <>
-        <h2 className="alert-anchor border-bottom">
-          {t('security_settings.OAuth.OIDC.name')}
-        </h2>
-
-        <div className="row  my-4">
-          <div className="offset-3 col-6">
-            <div className="form-check form-switch form-check-success">
-              <input
-                id="isOidcEnabled"
-                className="form-check-input"
-                type="checkbox"
-                checked={adminGeneralSecurityContainer.state.isOidcEnabled}
-                onChange={() => { adminGeneralSecurityContainer.switchIsOidcEnabled() }}
-              />
-              <label className="form-label form-check-label" htmlFor="isOidcEnabled">
-                {t('security_settings.OAuth.enable_oidc')}
-              </label>
-            </div>
-            {(!adminGeneralSecurityContainer.state.setupStrategies.includes('oidc') && isOidcEnabled)
-              && <div className="badge text-bg-warning">{t('security_settings.setup_is_not_yet_complete')}</div>}
-          </div>
-        </div>
-
-        <div className="row mb-5">
-          <label className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.callback_URL')}</label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              type="text"
-              value={oidcCallbackUrl}
-              readOnly
-            />
-            <p className="form-text text-muted small">{t('security_settings.desc_of_callback_URL', { AuthName: 'OAuth' })}</p>
-            {(siteUrl == null || siteUrl === '') && (
-              <div className="alert alert-danger">
-                <span className="material-symbols-outlined">error</span>
-                <span
-                  // eslint-disable-next-line max-len
-                  dangerouslySetInnerHTML={{ __html: t('alert.siteUrl_is_not_set', { link: `<a href="/admin/app">${t('headers.app_settings', { ns: 'commons' })}<span class="material-symbols-outlined">login</span></a>`, ns: 'commons' }) }}
-                />
-              </div>
-            )}
-          </div>
-        </div>
-
-        {isOidcEnabled && (
-          <>
-
-            <h3 className="border-bottom mb-4">{t('security_settings.configuration')}</h3>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcProviderName" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.providerName')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcProviderName"
-                  value={adminOidcSecurityContainer.state.oidcProviderName || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcProviderName(e.target.value)}
-                />
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcIssuerHost" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.issuerHost')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcIssuerHost"
-                  value={adminOidcSecurityContainer.state.oidcIssuerHost || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcIssuerHost(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_OIDC_ISSUER_HOST' }) }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcClientId" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.clientID')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcClientId"
-                  value={adminOidcSecurityContainer.state.oidcClientId || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcClientId(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_OIDC_CLIENT_ID' }) }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcClientSecret" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.client_secret')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcClientSecret"
-                  value={adminOidcSecurityContainer.state.oidcClientSecret || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcClientSecret(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_OIDC_CLIENT_SECRET' }) }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcAuthorizationEndpoint" className="text-start text-md-end col-md-3 col-form-label">
-                {t('security_settings.authorization_endpoint')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcAuthorizationEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcAuthorizationEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcAuthorizationEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcTokenEndpoint" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.token_endpoint')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcTokenEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcTokenEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcTokenEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcRevocationEndpoint" className="text-start text-md-end col-md-3 col-form-label">
-                {t('security_settings.revocation_endpoint')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcRevocationEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcRevocationEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcRevocationEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcIntrospectionEndpoint" className="text-start text-md-end col-md-3 col-form-label">
-                {t('security_settings.introspection_endpoint')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcIntrospectionEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcIntrospectionEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcIntrospectionEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcUserInfoEndpoint" className="text-start text-md-end col-md-3 col-form-label">
-                {t('security_settings.userinfo_endpoint')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcUserInfoEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcUserInfoEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcUserInfoEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcEndSessionEndpoint" className="text-start text-md-end col-md-3 col-form-label">
-                {t('security_settings.end_session_endpoint')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcEndSessionEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcEndSessionEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcEndSessionEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcRegistrationEndpoint" className="text-start text-md-end col-md-3 col-form-label">
-                {t('security_settings.registration_endpoint')}
-              </label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcRegistrationEndpoint"
-                  value={adminOidcSecurityContainer.state.oidcRegistrationEndpoint || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcRegistrationEndpoint(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcJWKSUri" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.jwks_uri')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcJWKSUri"
-                  value={adminOidcSecurityContainer.state.oidcJWKSUri || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcJWKSUri(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
-                </p>
-              </div>
-            </div>
-
-            <h3 className="alert-anchor border-bottom mb-4">
-              Attribute Mapping ({t('optional')})
-            </h3>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcAttrMapId" className="text-start text-md-end col-md-3 col-form-label">Identifier</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcAttrMapId"
-                  value={adminOidcSecurityContainer.state.oidcAttrMapId || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcAttrMapId(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.id_detail') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcAttrMapUserName" className="text-start text-md-end col-md-3 col-form-label">{t('username')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcAttrMapUserName"
-                  value={adminOidcSecurityContainer.state.oidcAttrMapUserName || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcAttrMapUserName(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.username_detail') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcAttrMapName" className="text-start text-md-end col-md-3 col-form-label">{t('Name')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcAttrMapName"
-                  value={adminOidcSecurityContainer.state.oidcAttrMapName || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcAttrMapName(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.name_detail') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label htmlFor="oidcAttrMapEmail" className="text-start text-md-end col-md-3 col-form-label">{t('Email')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  name="oidcAttrMapEmail"
-                  value={adminOidcSecurityContainer.state.oidcAttrMapEmail || ''}
-                  onChange={e => adminOidcSecurityContainer.changeOidcAttrMapEmail(e.target.value)}
-                />
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.mapping_detail', { target: t('Email') }) }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <label className="form-label text-start text-md-end col-md-3 col-form-label">{t('security_settings.callback_URL')}</label>
-              <div className="col-md-6">
-                <input
-                  className="form-control"
-                  type="text"
-                  defaultValue={oidcCallbackUrl}
-                  readOnly
-                />
-                <p className="form-text text-muted small">{t('security_settings.desc_of_callback_URL', { AuthName: 'OAuth' })}</p>
-                {(siteUrl == null || siteUrl === '') && (
-                  <div className="alert alert-danger">
-                    <span className="material-symbols-outlined">error</span>
-                    <span
-                      // eslint-disable-next-line max-len
-                      dangerouslySetInnerHTML={{ __html: t('alert.siteUrl_is_not_set', { link: `<a href="/admin/app">${t('headers.app_settings', { ns: 'commons' })}<span class="material-symbols-outlined">login</span></a>`, ns: 'commons' }) }}
-                    />
-                  </div>
-                )}
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <div className="offset-md-3 col-md-6">
-                <div className="form-check form-check-success">
-                  <input
-                    id="bindByUserName-oidc"
-                    className="form-check-input"
-                    type="checkbox"
-                    checked={adminOidcSecurityContainer.state.isSameUsernameTreatedAsIdenticalUser}
-                    onChange={() => { adminOidcSecurityContainer.switchIsSameUsernameTreatedAsIdenticalUser() }}
-                  />
-                  <label
-                    className="form-label form-check-label"
-                    htmlFor="bindByUserName-oidc"
-                    dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical') }}
-                  />
-                </div>
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical_warn') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row mb-4">
-              <div className="offset-md-3 col-md-6">
-                <div className="form-check form-check-success">
-                  <input
-                    id="bindByEmail-oidc"
-                    className="form-check-input"
-                    type="checkbox"
-                    checked={adminOidcSecurityContainer.state.isSameEmailTreatedAsIdenticalUser || false}
-                    onChange={() => { adminOidcSecurityContainer.switchIsSameEmailTreatedAsIdenticalUser() }}
-                  />
-                  <label
-                    className="form-label form-check-label"
-                    htmlFor="bindByEmail-oidc"
-                    dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical') }}
-                  />
-                </div>
-                <p className="form-text text-muted">
-                  <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical_warn') }} />
-                </p>
-              </div>
-            </div>
-
-            <div className="row my-3">
-              <div className="offset-3 col-5">
-                <button
-                  type="button"
-                  className="btn btn-primary"
-                  disabled={adminOidcSecurityContainer.state.retrieveError != null}
-                  onClick={this.onClickSubmit}
-                >
-                  {t('Update')}
-                </button>
-              </div>
-            </div>
-          </>
-        )}
-
-
-        <hr />
-
-        <div style={{ minHeight: '300px' }}>
-          <h4>
-            <span className="material-symbols-outlined" aria-hidden="true">help</span>
-            <a href="#collapseHelpForOidcOauth" data-bs-toggle="collapse"> {t('security_settings.OAuth.how_to.oidc')}</a>
-          </h4>
-          <div className=" card custom-card bg-body-tertiary">
-            <ol id="collapseHelpForOidcOauth" className="collapse mb-0">
-              <li>{t('security_settings.OAuth.OIDC.register_1')}</li>
-              <li dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.register_2', { url: oidcCallbackUrl }) }} />
-              <li>{t('security_settings.OAuth.OIDC.register_3')}</li>
-            </ol>
-          </div>
-        </div>
-
-      </>
-    );
-  }
-
-}
-
-OidcSecurityManagementContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
-  adminOidcSecurityContainer: PropTypes.instanceOf(AdminOidcSecurityContainer).isRequired,
-  siteUrl: PropTypes.string,
-};
-
-const OidcSecurityManagementContentsWrapperFC = (props) => {
-  const { t } = useTranslation('admin');
-  const siteUrl = useSiteUrlWithEmptyValueWarn();
-  return <OidcSecurityManagementContents t={t} {...props} siteUrl={siteUrl} />;
-};
-
-const OidcSecurityManagementContentsWrapper = withUnstatedContainers(OidcSecurityManagementContentsWrapperFC, [
-  AdminGeneralSecurityContainer,
-  AdminOidcSecurityContainer,
-]);
-
-export default OidcSecurityManagementContentsWrapper;

+ 488 - 0
apps/app/src/client/components/Admin/Security/OidcSecuritySettingContents.tsx

@@ -0,0 +1,488 @@
+import React, { useEffect, useCallback } from 'react';
+
+import { pathUtils } from '@growi/core/dist/utils';
+import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
+import urljoin from 'url-join';
+
+
+import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+import AdminOidcSecurityContainer from '~/client/services/AdminOidcSecurityContainer';
+import { toastSuccess, toastError } from '~/client/util/toastr';
+import { useSiteUrlWithEmptyValueWarn } from '~/states/global';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  adminOidcSecurityContainer: AdminOidcSecurityContainer;
+};
+
+const OidcSecurityManagementContents = (props: Props) => {
+  const { t } = useTranslation('admin');
+  const siteUrl = useSiteUrlWithEmptyValueWarn();
+
+  const {
+    adminGeneralSecurityContainer, adminOidcSecurityContainer,
+  } = props;
+  const { isOidcEnabled } = adminGeneralSecurityContainer.state;
+  const {
+    oidcProviderName, oidcIssuerHost, oidcClientId, oidcClientSecret,
+    oidcAuthorizationEndpoint, oidcTokenEndpoint, oidcRevocationEndpoint, oidcIntrospectionEndpoint,
+    oidcUserInfoEndpoint, oidcEndSessionEndpoint, oidcRegistrationEndpoint, oidcJWKSUri,
+    oidcAttrMapId, oidcAttrMapUserName, oidcAttrMapName, oidcAttrMapEmail,
+  } = adminOidcSecurityContainer.state;
+
+  const oidcCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/oidc/callback');
+
+  const { register, handleSubmit, reset } = useForm();
+
+  useEffect(() => {
+    reset({
+      oidcProviderName,
+      oidcIssuerHost,
+      oidcClientId,
+      oidcClientSecret,
+      oidcAuthorizationEndpoint,
+      oidcTokenEndpoint,
+      oidcRevocationEndpoint,
+      oidcIntrospectionEndpoint,
+      oidcUserInfoEndpoint,
+      oidcEndSessionEndpoint,
+      oidcRegistrationEndpoint,
+      oidcJWKSUri,
+      oidcAttrMapId,
+      oidcAttrMapUserName,
+      oidcAttrMapName,
+      oidcAttrMapEmail,
+    });
+  }, [
+    reset, oidcProviderName, oidcIssuerHost, oidcClientId, oidcClientSecret,
+    oidcAuthorizationEndpoint, oidcTokenEndpoint, oidcRevocationEndpoint, oidcIntrospectionEndpoint,
+    oidcUserInfoEndpoint, oidcEndSessionEndpoint, oidcRegistrationEndpoint, oidcJWKSUri,
+    oidcAttrMapId, oidcAttrMapUserName, oidcAttrMapName, oidcAttrMapEmail,
+  ]);
+
+  const onSubmit = useCallback(async(data) => {
+    try {
+      await adminOidcSecurityContainer.changeOidcProviderName(data.oidcProviderName);
+      await adminOidcSecurityContainer.changeOidcIssuerHost(data.oidcIssuerHost);
+      await adminOidcSecurityContainer.changeOidcClientId(data.oidcClientId);
+      await adminOidcSecurityContainer.changeOidcClientSecret(data.oidcClientSecret);
+      await adminOidcSecurityContainer.changeOidcAuthorizationEndpoint(data.oidcAuthorizationEndpoint);
+      await adminOidcSecurityContainer.changeOidcTokenEndpoint(data.oidcTokenEndpoint);
+      await adminOidcSecurityContainer.changeOidcRevocationEndpoint(data.oidcRevocationEndpoint);
+      await adminOidcSecurityContainer.changeOidcIntrospectionEndpoint(data.oidcIntrospectionEndpoint);
+      await adminOidcSecurityContainer.changeOidcUserInfoEndpoint(data.oidcUserInfoEndpoint);
+      await adminOidcSecurityContainer.changeOidcEndSessionEndpoint(data.oidcEndSessionEndpoint);
+      await adminOidcSecurityContainer.changeOidcRegistrationEndpoint(data.oidcRegistrationEndpoint);
+      await adminOidcSecurityContainer.changeOidcJWKSUri(data.oidcJWKSUri);
+      await adminOidcSecurityContainer.changeOidcAttrMapId(data.oidcAttrMapId);
+      await adminOidcSecurityContainer.changeOidcAttrMapUserName(data.oidcAttrMapUserName);
+      await adminOidcSecurityContainer.changeOidcAttrMapName(data.oidcAttrMapName);
+      await adminOidcSecurityContainer.changeOidcAttrMapEmail(data.oidcAttrMapEmail);
+      await adminOidcSecurityContainer.updateOidcSetting();
+      await adminGeneralSecurityContainer.retrieveSetupStratedies();
+      toastSuccess(t('security_settings.OAuth.OIDC.updated_oidc'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [t, adminOidcSecurityContainer, adminGeneralSecurityContainer]);
+
+  return (
+    <>
+      <h2 className="alert-anchor border-bottom">
+        {t('security_settings.OAuth.OIDC.name')}
+      </h2>
+
+      <div className="row  my-4">
+        <div className="offset-3 col-6">
+          <div className="form-check form-switch form-check-success">
+            <input
+              id="isOidcEnabled"
+              className="form-check-input"
+              type="checkbox"
+              checked={adminGeneralSecurityContainer.state.isOidcEnabled}
+              onChange={() => { adminGeneralSecurityContainer.switchIsOidcEnabled() }}
+            />
+            <label className="form-label form-check-label" htmlFor="isOidcEnabled">
+              {t('security_settings.OAuth.enable_oidc')}
+            </label>
+          </div>
+          {(!adminGeneralSecurityContainer.state.setupStrategies.includes('oidc') && isOidcEnabled)
+              && <div className="badge text-bg-warning">{t('security_settings.setup_is_not_yet_complete')}</div>}
+        </div>
+      </div>
+
+      <div className="row mb-5">
+        <label className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.callback_URL')}</label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            type="text"
+            value={oidcCallbackUrl}
+            readOnly
+          />
+          <p className="form-text text-muted small">{t('security_settings.desc_of_callback_URL', { AuthName: 'OAuth' })}</p>
+          {(siteUrl == null || siteUrl === '') && (
+            <div className="alert alert-danger">
+              <span className="material-symbols-outlined">error</span>
+              <span
+                // eslint-disable-next-line max-len
+                dangerouslySetInnerHTML={{ __html: t('alert.siteUrl_is_not_set', { link: `<a href="/admin/app">${t('headers.app_settings', { ns: 'commons' })}<span class="material-symbols-outlined">login</span></a>`, ns: 'commons' }) }}
+              />
+            </div>
+          )}
+        </div>
+      </div>
+
+      {isOidcEnabled && (
+        <form onSubmit={handleSubmit(onSubmit)}>
+
+          <h3 className="border-bottom mb-4">{t('security_settings.configuration')}</h3>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcProviderName" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.providerName')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcProviderName')}
+              />
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcIssuerHost" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.issuerHost')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcIssuerHost')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_OIDC_ISSUER_HOST' }) }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcClientId" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.clientID')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcClientId')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_OIDC_CLIENT_ID' }) }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcClientSecret" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.client_secret')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcClientSecret')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Use env var if empty', { env: 'OAUTH_OIDC_CLIENT_SECRET' }) }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcAuthorizationEndpoint" className="text-start text-md-end col-md-3 col-form-label">
+              {t('security_settings.authorization_endpoint')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcAuthorizationEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcTokenEndpoint" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.token_endpoint')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcTokenEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcRevocationEndpoint" className="text-start text-md-end col-md-3 col-form-label">
+              {t('security_settings.revocation_endpoint')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcRevocationEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcIntrospectionEndpoint" className="text-start text-md-end col-md-3 col-form-label">
+              {t('security_settings.introspection_endpoint')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcIntrospectionEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcUserInfoEndpoint" className="text-start text-md-end col-md-3 col-form-label">
+              {t('security_settings.userinfo_endpoint')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcUserInfoEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcEndSessionEndpoint" className="text-start text-md-end col-md-3 col-form-label">
+              {t('security_settings.end_session_endpoint')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcEndSessionEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcRegistrationEndpoint" className="text-start text-md-end col-md-3 col-form-label">
+              {t('security_settings.registration_endpoint')}
+            </label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcRegistrationEndpoint')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcJWKSUri" className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.jwks_uri')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcJWKSUri')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.Use discovered URL if empty') }} />
+              </p>
+            </div>
+          </div>
+
+          <h3 className="alert-anchor border-bottom mb-4">
+            Attribute Mapping ({t('optional')})
+          </h3>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcAttrMapId" className="text-start text-md-end col-md-3 col-form-label">Identifier</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcAttrMapId')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.id_detail') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcAttrMapUserName" className="text-start text-md-end col-md-3 col-form-label">{t('username')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcAttrMapUserName')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.username_detail') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcAttrMapName" className="text-start text-md-end col-md-3 col-form-label">{t('Name')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcAttrMapName')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.name_detail') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label htmlFor="oidcAttrMapEmail" className="text-start text-md-end col-md-3 col-form-label">{t('Email')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                {...register('oidcAttrMapEmail')}
+              />
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.mapping_detail', { target: t('Email') }) }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <label className="form-label text-start text-md-end col-md-3 col-form-label">{t('security_settings.callback_URL')}</label>
+            <div className="col-md-6">
+              <input
+                className="form-control"
+                type="text"
+                defaultValue={oidcCallbackUrl}
+                readOnly
+              />
+              <p className="form-text text-muted small">{t('security_settings.desc_of_callback_URL', { AuthName: 'OAuth' })}</p>
+              {(siteUrl == null || siteUrl === '') && (
+                <div className="alert alert-danger">
+                  <span className="material-symbols-outlined">error</span>
+                  <span
+                    // eslint-disable-next-line max-len
+                    dangerouslySetInnerHTML={{ __html: t('alert.siteUrl_is_not_set', { link: `<a href="/admin/app">${t('headers.app_settings', { ns: 'commons' })}<span class="material-symbols-outlined">login</span></a>`, ns: 'commons' }) }}
+                  />
+                </div>
+              )}
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <div className="offset-md-3 col-md-6">
+              <div className="form-check form-check-success">
+                <input
+                  id="bindByUserName-oidc"
+                  className="form-check-input"
+                  type="checkbox"
+                  checked={adminOidcSecurityContainer.state.isSameUsernameTreatedAsIdenticalUser}
+                  onChange={() => { adminOidcSecurityContainer.switchIsSameUsernameTreatedAsIdenticalUser() }}
+                />
+                <label
+                  className="form-label form-check-label"
+                  htmlFor="bindByUserName-oidc"
+                  dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical') }}
+                />
+              </div>
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical_warn') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row mb-4">
+            <div className="offset-md-3 col-md-6">
+              <div className="form-check form-check-success">
+                <input
+                  id="bindByEmail-oidc"
+                  className="form-check-input"
+                  type="checkbox"
+                  checked={adminOidcSecurityContainer.state.isSameEmailTreatedAsIdenticalUser || false}
+                  onChange={() => { adminOidcSecurityContainer.switchIsSameEmailTreatedAsIdenticalUser() }}
+                />
+                <label
+                  className="form-label form-check-label"
+                  htmlFor="bindByEmail-oidc"
+                  dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical') }}
+                />
+              </div>
+              <p className="form-text text-muted">
+                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical_warn') }} />
+              </p>
+            </div>
+          </div>
+
+          <div className="row my-3">
+            <div className="offset-3 col-5">
+              <button
+                type="submit"
+                className="btn btn-primary"
+                disabled={adminOidcSecurityContainer.state.retrieveError != null}
+              >
+                {t('Update')}
+              </button>
+            </div>
+          </div>
+        </form>
+      )}
+
+
+      <hr />
+
+      <div style={{ minHeight: '300px' }}>
+        <h4>
+          <span className="material-symbols-outlined" aria-hidden="true">help</span>
+          <a href="#collapseHelpForOidcOauth" data-bs-toggle="collapse"> {t('security_settings.OAuth.how_to.oidc')}</a>
+        </h4>
+        <div className=" card custom-card bg-body-tertiary">
+          <ol id="collapseHelpForOidcOauth" className="collapse mb-0">
+            <li>{t('security_settings.OAuth.OIDC.register_1')}</li>
+            <li dangerouslySetInnerHTML={{ __html: t('security_settings.OAuth.OIDC.register_2', { url: oidcCallbackUrl }) }} />
+            <li>{t('security_settings.OAuth.OIDC.register_3')}</li>
+          </ol>
+        </div>
+      </div>
+
+    </>
+  );
+};
+
+const OidcSecurityManagementContentsWrapper = withUnstatedContainers(OidcSecurityManagementContents, [
+  AdminGeneralSecurityContainer,
+  AdminOidcSecurityContainer,
+]);
+
+export default OidcSecurityManagementContentsWrapper;

+ 0 - 563
apps/app/src/client/components/Admin/Security/SamlSecuritySettingContents.jsx

@@ -1,563 +0,0 @@
-/* eslint-disable react/no-danger */
-import React from 'react';
-
-import { pathUtils } from '@growi/core/dist/utils';
-import { useTranslation } from 'next-i18next';
-import PropTypes from 'prop-types';
-import { Collapse } from 'reactstrap';
-import urljoin from 'url-join';
-
-
-import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
-import AdminSamlSecurityContainer from '~/client/services/AdminSamlSecurityContainer';
-import { toastSuccess, toastError } from '~/client/util/toastr';
-import { useSiteUrlWithEmptyValueWarn } from '~/states/global';
-
-import { withUnstatedContainers } from '../../UnstatedUtils';
-
-
-class SamlSecurityManagementContents extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      isHelpOpened: false,
-    };
-
-    this.onClickSubmit = this.onClickSubmit.bind(this);
-  }
-
-  async onClickSubmit() {
-    const { t, adminSamlSecurityContainer, adminGeneralSecurityContainer } = this.props;
-
-    try {
-      await adminSamlSecurityContainer.updateSamlSetting();
-      toastSuccess(t('security_settings.SAML.updated_saml'));
-    }
-    catch (err) {
-      toastError(err);
-    }
-
-    try {
-      await adminGeneralSecurityContainer.retrieveSetupStratedies();
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  render() {
-    const {
-      t, adminGeneralSecurityContainer, adminSamlSecurityContainer, siteUrl,
-    } = this.props;
-    const { useOnlyEnvVars } = adminSamlSecurityContainer.state;
-    const { isSamlEnabled } = adminGeneralSecurityContainer.state;
-
-    const samlCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/saml/callback');
-
-    return (
-      <React.Fragment>
-
-        <h2 className="alert-anchor border-bottom">
-          {t('security_settings.SAML.name')}
-        </h2>
-
-        {useOnlyEnvVars && (
-          <p
-            className="alert alert-info"
-            dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.note for the only env option', { env: 'SAML_USES_ONLY_ENV_VARS_FOR_SOME_OPTIONS' }) }}
-          />
-        )}
-
-        <div className="row mt-4 mb-5">
-          <div className="col-6 offset-3">
-            <div className="form-check form-switch form-check-success">
-              <input
-                id="isSamlEnabled"
-                className="form-check-input"
-                type="checkbox"
-                checked={adminGeneralSecurityContainer.state.isSamlEnabled}
-                onChange={() => { adminGeneralSecurityContainer.switchIsSamlEnabled() }}
-                disabled={adminSamlSecurityContainer.state.useOnlyEnvVars}
-              />
-              <label className="form-label form-check-label" htmlFor="isSamlEnabled">
-                {t('security_settings.SAML.enable_saml')}
-              </label>
-            </div>
-            {(!adminGeneralSecurityContainer.state.setupStrategies.includes('saml') && isSamlEnabled)
-              && <div className="badge text-bg-warning">{t('security_settings.setup_is_not_yet_complete')}</div>}
-          </div>
-        </div>
-
-        <div className="row mb-5">
-          <label className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.callback_URL')}</label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              type="text"
-              defaultValue={samlCallbackUrl}
-              readOnly
-            />
-            <p className="form-text text-muted small">{t('security_settings.desc_of_callback_URL', { AuthName: 'SAML Identity' })}</p>
-            {(siteUrl == null || siteUrl === '') && (
-              <div className="alert alert-danger">
-                <span className="material-symbols-outlined">error</span>
-                <span
-                  // eslint-disable-next-line max-len
-                  dangerouslySetInnerHTML={{ __html: t('alert.siteUrl_is_not_set', { link: `<a href="/admin/app">${t('headers.app_settings', { ns: 'commons' })}<span class="material-symbols-outlined">login</span></a>`, ns: 'commons' }) }}
-                />
-              </div>
-            )}
-          </div>
-        </div>
-
-        {isSamlEnabled && (
-          <React.Fragment>
-
-            {(adminSamlSecurityContainer.state.missingMandatoryConfigKeys.length !== 0) && (
-              <div className="alert alert-danger">
-                {t('security_settings.missing mandatory configs')}
-                <ul className="mb-0">
-                  {adminSamlSecurityContainer.state.missingMandatoryConfigKeys.map((configKey) => {
-                    const key = configKey.replace('security:passport-saml:', '');
-                    return <li key={configKey}>{t(`security_settings.form_item_name.${key}`)}</li>;
-                  })}
-                </ul>
-              </div>
-            )}
-
-
-            <h3 className="alert-anchor border-bottom mb-3">
-              Basic Settings
-            </h3>
-
-            <table className={`table settings-table ${useOnlyEnvVars && 'use-only-env-vars'}`}>
-              <colgroup>
-                <col className="item-name" />
-                <col className="from-db" />
-                <col className="from-env-vars" />
-              </colgroup>
-              <thead>
-                <tr><th></th><th>Database</th><th>Environment variables</th></tr>
-              </thead>
-              <tbody>
-                <tr>
-                  <th>{t('security_settings.form_item_name.entryPoint')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      name="samlEntryPoint"
-                      readOnly={useOnlyEnvVars}
-                      value={adminSamlSecurityContainer.state.samlEntryPoint}
-                      onChange={e => adminSamlSecurityContainer.changeSamlEntryPoint(e.target.value)}
-                    />
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envEntryPoint || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ENTRY_POINT' }) }} />
-                    </p>
-                  </td>
-                </tr>
-                <tr>
-                  <th>{t('security_settings.form_item_name.issuer')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      name="samlEnvVarissuer"
-                      readOnly={useOnlyEnvVars}
-                      value={adminSamlSecurityContainer.state.samlIssuer}
-                      onChange={e => adminSamlSecurityContainer.changeSamlIssuer(e.target.value)}
-                    />
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envIssuer || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ISSUER' }) }} />
-                    </p>
-                  </td>
-                </tr>
-                <tr>
-                  <th>{t('security_settings.form_item_name.cert')}</th>
-                  <td>
-                    <textarea
-                      className="form-control form-control-sm"
-                      type="text"
-                      rows="5"
-                      name="samlCert"
-                      readOnly={useOnlyEnvVars}
-                      value={adminSamlSecurityContainer.state.samlCert}
-                      onChange={e => adminSamlSecurityContainer.changeSamlCert(e.target.value)}
-                    />
-                    <p>
-                      <small>
-                        {t('security_settings.SAML.cert_detail')}
-                      </small>
-                    </p>
-                    <div>
-                      <small>
-                        e.g.
-                        <pre className="card custom-card">{`-----BEGIN CERTIFICATE-----
-MIICBzCCAXACCQD4US7+0A/b/zANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJK
-UDEOMAwGA1UECAwFVG9reW8xFTATBgNVBAoMDFdFU0VFSywgSW5jLjESMBAGA1UE
-...
-crmVwBzbloUO2l6k1ibwD2WVwpdxMKIF5z58HfKAvxZAzCHE7kMEZr1ge30WRXQA
-pWVdnzS1VCO8fKsJ7YYIr+JmHvseph3kFUOI5RqkCcMZlKUv83aUThsTHw==
------END CERTIFICATE-----
-                        `}
-                        </pre>
-                      </small>
-                    </div>
-                  </td>
-                  <td>
-                    <textarea
-                      className="form-control form-control-sm"
-                      type="text"
-                      rows="5"
-                      readOnly
-                      value={adminSamlSecurityContainer.state.envCert || ''}
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_CERT' }) }} />
-                    </p>
-                  </td>
-                </tr>
-              </tbody>
-            </table>
-
-            <h3 className="alert-anchor border-bottom mt-5 mb-3">
-              Attribute Mapping
-            </h3>
-
-            <table className="table settings-table">
-              <colgroup>
-                <col className="item-name" />
-                <col className="from-db" />
-                <col className="from-env-vars" />
-              </colgroup>
-              <thead>
-                <tr><th></th><th>Database</th><th>Environment variables</th></tr>
-              </thead>
-              <tbody>
-                <tr>
-                  <th>{t('security_settings.form_item_name.attrMapId')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.samlAttrMapId}
-                      onChange={e => adminSamlSecurityContainer.changeSamlAttrMapId(e.target.value)}
-                    />
-                    <p className="form-text text-muted">
-                      <small>
-                        {t('security_settings.SAML.id_detail')}
-                      </small>
-                    </p>
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envAttrMapId || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_ID' }) }} />
-                    </p>
-                  </td>
-                </tr>
-                <tr>
-                  <th>{t('security_settings.form_item_name.attrMapUsername')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.samlAttrMapUsername}
-                      onChange={e => adminSamlSecurityContainer.changeSamlAttrMapUserName(e.target.value)}
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.username_detail') }} />
-                    </p>
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envAttrMapUsername || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_USERNAME' }) }} />
-                    </p>
-                  </td>
-                </tr>
-                <tr>
-                  <th>{t('security_settings.form_item_name.attrMapMail')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.samlAttrMapMail}
-                      onChange={e => adminSamlSecurityContainer.changeSamlAttrMapMail(e.target.value)}
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.mapping_detail', { target: 'Email' }) }} />
-                    </p>
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envAttrMapMail || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_MAIL' }) }} />
-                    </p>
-                  </td>
-                </tr>
-                <tr>
-                  <th>{t('security_settings.form_item_name.attrMapFirstName')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.samlAttrMapFirstName}
-                      onChange={e => adminSamlSecurityContainer.changeSamlAttrMapFirstName(e.target.value)}
-                    />
-                    <p className="form-text text-muted">
-                      {/* eslint-disable-next-line max-len */}
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.mapping_detail', { target: t('security_settings.form_item_name.attrMapFirstName') }) }} />
-                    </p>
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envAttrMapFirstName || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small>
-                        <span dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_FIRST_NAME' }) }} />
-                        <br />
-                        <span dangerouslySetInnerHTML={{ __html: t('security_settings.Use default if both are empty', { target: 'firstName' }) }} />
-                      </small>
-                    </p>
-                  </td>
-                </tr>
-                <tr>
-                  <th>{t('security_settings.form_item_name.attrMapLastName')}</th>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.samlAttrMapLastName}
-                      onChange={e => adminSamlSecurityContainer.changeSamlAttrMapLastName(e.target.value)}
-                    />
-                    <p className="form-text text-muted">
-                      {/* eslint-disable-next-line max-len */}
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.mapping_detail', { target: t('security_settings.form_item_name.attrMapLastName') }) }} />
-                    </p>
-                  </td>
-                  <td>
-                    <input
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envAttrMapLastName || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small>
-                        <span dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_LAST_NAME' }) }} />
-                        <br />
-                        <span dangerouslySetInnerHTML={{ __html: t('security_settings.Use default if both are empty', { target: 'lastName' }) }} />
-                      </small>
-                    </p>
-                  </td>
-                </tr>
-              </tbody>
-            </table>
-
-            <h3 className="alert-anchor border-bottom mt-5 mb-4">
-              Attribute Mapping Options
-            </h3>
-
-            <div className="row ms-3">
-              <div className="form-check form-check-success">
-                <input
-                  id="bindByUserName-SAML"
-                  className="form-check-input"
-                  type="checkbox"
-                  checked={adminSamlSecurityContainer.state.isSameUsernameTreatedAsIdenticalUser || false}
-                  onChange={() => { adminSamlSecurityContainer.switchIsSameUsernameTreatedAsIdenticalUser() }}
-                />
-                <label
-                  className="form-label form-check-label"
-                  htmlFor="bindByUserName-SAML"
-                  dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical') }}
-                />
-              </div>
-              <p className="form-text text-muted">
-                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical_warn') }} />
-              </p>
-            </div>
-
-            <div className="row mb-5 ms-3">
-              <div className="form-check form-check-success">
-                <input
-                  id="bindByEmail-SAML"
-                  className="form-check-input"
-                  type="checkbox"
-                  checked={adminSamlSecurityContainer.state.isSameEmailTreatedAsIdenticalUser || false}
-                  onChange={() => { adminSamlSecurityContainer.switchIsSameEmailTreatedAsIdenticalUser() }}
-                />
-                <label
-                  className="form-label form-check-label"
-                  htmlFor="bindByEmail-SAML"
-                  dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical') }}
-                />
-              </div>
-              <p className="form-text text-muted">
-                <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical_warn') }} />
-              </p>
-            </div>
-
-            <h3 className="alert-anchor border-bottom mb-4">
-              Attribute-based Login Control
-            </h3>
-
-            <p className="form-text text-muted">
-              <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_detail') }} />
-            </p>
-
-            <table className="table settings-table">
-              <colgroup>
-                <col className="item-name" />
-                <col className="from-db" />
-                <col className="from-env-vars" />
-              </colgroup>
-              <thead>
-                <tr><th></th><th>Database</th><th>Environment variables</th></tr>
-              </thead>
-              <tbody>
-                <tr>
-                  <th>
-                    { t('security_settings.form_item_name.ABLCRule') }
-                  </th>
-                  <td>
-                    <textarea
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.samlABLCRule || ''}
-                      onChange={(e) => { adminSamlSecurityContainer.changeSamlABLCRule(e.target.value) }}
-                    />
-                    <div className="mt-2">
-                      <p>
-                        See&nbsp;
-                        <a
-                          href="https://lucene.apache.org/core/2_9_4/queryparsersyntax.html"
-                          target="_blank"
-                          rel="noreferer noreferrer"
-                        >
-                          Apache Lucene - Query Parser Syntax <span className="growi-custom-icons">external_link</span>
-                        </a>.
-                      </p>
-                      <div className="accordion" id="accordionId">
-                        <div className="accordion-item p-1">
-                          <h2 className="accordion-header">
-                            <button
-                              className="btn btn-link text-start"
-                              type="button"
-                              onClick={() => this.setState({ isHelpOpened: !this.state.isHelpOpened })}
-                              aria-expanded="true"
-                              aria-controls="ablchelp"
-                            >
-                              <span
-                                className="material-symbols-outlined me-1"
-                                small
-                              >{this.state.isHelpOpened ? 'expand_more' : 'chevron_right'}
-                              </span> Show more...
-                            </button>
-                          </h2>
-                          <Collapse isOpen={this.state.isHelpOpened}>
-                            <div className="accordion-body">
-                              <p dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_rule_help') }} />
-                              <p dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_rule_example1') }} />
-                              <p dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_rule_example2') }} />
-                            </div>
-                          </Collapse>
-                        </div>
-                      </div>
-                    </div>
-                  </td>
-                  <td>
-                    <textarea
-                      className="form-control"
-                      type="text"
-                      value={adminSamlSecurityContainer.state.envABLCRule || ''}
-                      readOnly
-                    />
-                    <p className="form-text text-muted">
-                      <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ABLC_RULE' }) }} />
-                    </p>
-                  </td>
-                </tr>
-              </tbody>
-            </table>
-
-            <div className="row my-3">
-              <div className="offset-3 col-5">
-                <button
-                  type="button"
-                  className="btn btn-primary"
-                  disabled={adminSamlSecurityContainer.state.retrieveError != null}
-                  onClick={this.onClickSubmit}
-                >
-                  {t('Update')}
-                </button>
-              </div>
-            </div>
-
-          </React.Fragment>
-        )}
-
-      </React.Fragment>
-    );
-
-  }
-
-}
-
-SamlSecurityManagementContents.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
-  adminSamlSecurityContainer: PropTypes.instanceOf(AdminSamlSecurityContainer).isRequired,
-  siteUrl: PropTypes.string.isRequired,
-};
-
-const SamlSecurityManagementContentsWrapperFC = (props) => {
-  const { t } = useTranslation('admin');
-  const siteUrl = useSiteUrlWithEmptyValueWarn();
-  return <SamlSecurityManagementContents t={t} siteUrl={siteUrl} {...props} />;
-};
-
-const SamlSecurityManagementContentsWrapper = withUnstatedContainers(SamlSecurityManagementContentsWrapperFC, [
-  AdminGeneralSecurityContainer,
-  AdminSamlSecurityContainer,
-]);
-
-export default SamlSecurityManagementContentsWrapper;

+ 549 - 0
apps/app/src/client/components/Admin/Security/SamlSecuritySettingContents.tsx

@@ -0,0 +1,549 @@
+/* eslint-disable react/no-danger */
+import React, { useState, useEffect, useCallback } from 'react';
+
+import { pathUtils } from '@growi/core/dist/utils';
+import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
+import { Collapse } from 'reactstrap';
+import urljoin from 'url-join';
+
+
+import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+import AdminSamlSecurityContainer from '~/client/services/AdminSamlSecurityContainer';
+import { toastSuccess, toastError } from '~/client/util/toastr';
+import { useSiteUrlWithEmptyValueWarn } from '~/states/global';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  adminSamlSecurityContainer: AdminSamlSecurityContainer;
+};
+
+const SamlSecurityManagementContents = (props: Props) => {
+  const {
+    adminGeneralSecurityContainer, adminSamlSecurityContainer,
+  } = props;
+
+  const { t } = useTranslation('admin');
+  const siteUrl = useSiteUrlWithEmptyValueWarn();
+
+  const [isHelpOpened, setIsHelpOpened] = useState(false);
+  const { register, handleSubmit, reset } = useForm();
+
+  useEffect(() => {
+    reset({
+      samlEntryPoint: adminSamlSecurityContainer.state.samlEntryPoint || '',
+      samlIssuer: adminSamlSecurityContainer.state.samlIssuer || '',
+      samlCert: adminSamlSecurityContainer.state.samlCert || '',
+      samlAttrMapId: adminSamlSecurityContainer.state.samlAttrMapId || '',
+      samlAttrMapUsername: adminSamlSecurityContainer.state.samlAttrMapUsername || '',
+      samlAttrMapMail: adminSamlSecurityContainer.state.samlAttrMapMail || '',
+      samlAttrMapFirstName: adminSamlSecurityContainer.state.samlAttrMapFirstName || '',
+      samlAttrMapLastName: adminSamlSecurityContainer.state.samlAttrMapLastName || '',
+      samlABLCRule: adminSamlSecurityContainer.state.samlABLCRule || '',
+    });
+  }, [adminSamlSecurityContainer.state, reset]);
+
+  const onSubmit = useCallback(async(data) => {
+    adminSamlSecurityContainer.changeSamlEntryPoint(data.samlEntryPoint);
+    adminSamlSecurityContainer.changeSamlIssuer(data.samlIssuer);
+    adminSamlSecurityContainer.changeSamlCert(data.samlCert);
+    adminSamlSecurityContainer.changeSamlAttrMapId(data.samlAttrMapId);
+    adminSamlSecurityContainer.changeSamlAttrMapUserName(data.samlAttrMapUsername);
+    adminSamlSecurityContainer.changeSamlAttrMapMail(data.samlAttrMapMail);
+    adminSamlSecurityContainer.changeSamlAttrMapFirstName(data.samlAttrMapFirstName);
+    adminSamlSecurityContainer.changeSamlAttrMapLastName(data.samlAttrMapLastName);
+    adminSamlSecurityContainer.changeSamlABLCRule(data.samlABLCRule);
+
+    try {
+      await adminSamlSecurityContainer.updateSamlSetting();
+      toastSuccess(t('security_settings.SAML.updated_saml'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+    try {
+      await adminGeneralSecurityContainer.retrieveSetupStratedies();
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [adminSamlSecurityContainer, adminGeneralSecurityContainer, t]);
+
+  const { useOnlyEnvVars } = adminSamlSecurityContainer.state;
+  const { isSamlEnabled } = adminGeneralSecurityContainer.state;
+
+  const samlCallbackUrl = urljoin(pathUtils.removeTrailingSlash(siteUrl), '/passport/saml/callback');
+
+  return (
+    <React.Fragment>
+
+      <h2 className="alert-anchor border-bottom">
+        {t('security_settings.SAML.name')}
+      </h2>
+
+      {useOnlyEnvVars && (
+        <p
+          className="alert alert-info"
+          dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.note for the only env option', { env: 'SAML_USES_ONLY_ENV_VARS_FOR_SOME_OPTIONS' }) }}
+        />
+      )}
+
+      <div className="row mt-4 mb-5">
+        <div className="col-6 offset-3">
+          <div className="form-check form-switch form-check-success">
+            <input
+              id="isSamlEnabled"
+              className="form-check-input"
+              type="checkbox"
+              checked={adminGeneralSecurityContainer.state.isSamlEnabled}
+              onChange={() => { adminGeneralSecurityContainer.switchIsSamlEnabled() }}
+              disabled={adminSamlSecurityContainer.state.useOnlyEnvVars}
+            />
+            <label className="form-label form-check-label" htmlFor="isSamlEnabled">
+              {t('security_settings.SAML.enable_saml')}
+            </label>
+          </div>
+          {(!adminGeneralSecurityContainer.state.setupStrategies.includes('saml') && isSamlEnabled)
+              && <div className="badge text-bg-warning">{t('security_settings.setup_is_not_yet_complete')}</div>}
+        </div>
+      </div>
+
+      <div className="row mb-5">
+        <label className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.callback_URL')}</label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            type="text"
+            defaultValue={samlCallbackUrl}
+            readOnly
+          />
+          <p className="form-text text-muted small">{t('security_settings.desc_of_callback_URL', { AuthName: 'SAML Identity' })}</p>
+          {(siteUrl == null || siteUrl === '') && (
+            <div className="alert alert-danger">
+              <span className="material-symbols-outlined">error</span>
+              <span
+                // eslint-disable-next-line max-len
+                dangerouslySetInnerHTML={{ __html: t('alert.siteUrl_is_not_set', { link: `<a href="/admin/app">${t('headers.app_settings', { ns: 'commons' })}<span class="material-symbols-outlined">login</span></a>`, ns: 'commons' }) }}
+              />
+            </div>
+          )}
+        </div>
+      </div>
+
+      {isSamlEnabled && (
+        <form onSubmit={handleSubmit(onSubmit)}>
+
+          {(adminSamlSecurityContainer.state.missingMandatoryConfigKeys.length !== 0) && (
+            <div className="alert alert-danger">
+              {t('security_settings.missing mandatory configs')}
+              <ul className="mb-0">
+                {adminSamlSecurityContainer.state.missingMandatoryConfigKeys.map((configKey) => {
+                  const key = configKey.replace('security:passport-saml:', '');
+                  return <li key={configKey}>{t(`security_settings.form_item_name.${key}`)}</li>;
+                })}
+              </ul>
+            </div>
+          )}
+
+
+          <h3 className="alert-anchor border-bottom mb-3">
+            Basic Settings
+          </h3>
+
+          <table className={`table settings-table ${useOnlyEnvVars && 'use-only-env-vars'}`}>
+            <colgroup>
+              <col className="item-name" />
+              <col className="from-db" />
+              <col className="from-env-vars" />
+            </colgroup>
+            <thead>
+              <tr><th></th><th>Database</th><th>Environment variables</th></tr>
+            </thead>
+            <tbody>
+              <tr>
+                <th>{t('security_settings.form_item_name.entryPoint')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    readOnly={useOnlyEnvVars}
+                    {...register('samlEntryPoint')}
+                  />
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envEntryPoint || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ENTRY_POINT' }) }} />
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <th>{t('security_settings.form_item_name.issuer')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    readOnly={useOnlyEnvVars}
+                    {...register('samlIssuer')}
+                  />
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envIssuer || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ISSUER' }) }} />
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <th>{t('security_settings.form_item_name.cert')}</th>
+                <td>
+                  <textarea
+                    className="form-control form-control-sm"
+                    rows={5}
+                    readOnly={useOnlyEnvVars}
+                    {...register('samlCert')}
+                  />
+                  <p>
+                    <small>
+                      {t('security_settings.SAML.cert_detail')}
+                    </small>
+                  </p>
+                  <div>
+                    <small>
+                      e.g.
+                      <pre className="card custom-card">{`-----BEGIN CERTIFICATE-----
+MIICBzCCAXACCQD4US7+0A/b/zANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJK
+UDEOMAwGA1UECAwFVG9reW8xFTATBgNVBAoMDFdFU0VFSywgSW5jLjESMBAGA1UE
+...
+crmVwBzbloUO2l6k1ibwD2WVwpdxMKIF5z58HfKAvxZAzCHE7kMEZr1ge30WRXQA
+pWVdnzS1VCO8fKsJ7YYIr+JmHvseph3kFUOI5RqkCcMZlKUv83aUThsTHw==
+-----END CERTIFICATE-----
+                        `}
+                      </pre>
+                    </small>
+                  </div>
+                </td>
+                <td>
+                  <textarea
+                    className="form-control form-control-sm"
+                    rows={5}
+                    readOnly
+                    value={adminSamlSecurityContainer.state.envCert || ''}
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_CERT' }) }} />
+                  </p>
+                </td>
+              </tr>
+            </tbody>
+          </table>
+
+          <h3 className="alert-anchor border-bottom mt-5 mb-3">
+            Attribute Mapping
+          </h3>
+
+          <table className="table settings-table">
+            <colgroup>
+              <col className="item-name" />
+              <col className="from-db" />
+              <col className="from-env-vars" />
+            </colgroup>
+            <thead>
+              <tr><th></th><th>Database</th><th>Environment variables</th></tr>
+            </thead>
+            <tbody>
+              <tr>
+                <th>{t('security_settings.form_item_name.attrMapId')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    {...register('samlAttrMapId')}
+                  />
+                  <p className="form-text text-muted">
+                    <small>
+                      {t('security_settings.SAML.id_detail')}
+                    </small>
+                  </p>
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envAttrMapId || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_ID' }) }} />
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <th>{t('security_settings.form_item_name.attrMapUsername')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    {...register('samlAttrMapUsername')}
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.username_detail') }} />
+                  </p>
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envAttrMapUsername || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_USERNAME' }) }} />
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <th>{t('security_settings.form_item_name.attrMapMail')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    {...register('samlAttrMapMail')}
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.mapping_detail', { target: 'Email' }) }} />
+                  </p>
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envAttrMapMail || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_MAIL' }) }} />
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <th>{t('security_settings.form_item_name.attrMapFirstName')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    {...register('samlAttrMapFirstName')}
+                  />
+                  <p className="form-text text-muted">
+                    {/* eslint-disable-next-line max-len */}
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.mapping_detail', { target: t('security_settings.form_item_name.attrMapFirstName') }) }} />
+                  </p>
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envAttrMapFirstName || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small>
+                      <span dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_FIRST_NAME' }) }} />
+                      <br />
+                      <span dangerouslySetInnerHTML={{ __html: t('security_settings.Use default if both are empty', { target: 'firstName' }) }} />
+                    </small>
+                  </p>
+                </td>
+              </tr>
+              <tr>
+                <th>{t('security_settings.form_item_name.attrMapLastName')}</th>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    {...register('samlAttrMapLastName')}
+                  />
+                  <p className="form-text text-muted">
+                    {/* eslint-disable-next-line max-len */}
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.mapping_detail', { target: t('security_settings.form_item_name.attrMapLastName') }) }} />
+                  </p>
+                </td>
+                <td>
+                  <input
+                    className="form-control"
+                    type="text"
+                    value={adminSamlSecurityContainer.state.envAttrMapLastName || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small>
+                      <span dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ATTR_MAPPING_LAST_NAME' }) }} />
+                      <br />
+                      <span dangerouslySetInnerHTML={{ __html: t('security_settings.Use default if both are empty', { target: 'lastName' }) }} />
+                    </small>
+                  </p>
+                </td>
+              </tr>
+            </tbody>
+          </table>
+
+          <h3 className="alert-anchor border-bottom mt-5 mb-4">
+            Attribute Mapping Options
+          </h3>
+
+          <div className="row ms-3">
+            <div className="form-check form-check-success">
+              <input
+                id="bindByUserName-SAML"
+                className="form-check-input"
+                type="checkbox"
+                checked={adminSamlSecurityContainer.state.isSameUsernameTreatedAsIdenticalUser || false}
+                onChange={() => { adminSamlSecurityContainer.switchIsSameUsernameTreatedAsIdenticalUser() }}
+              />
+              <label
+                className="form-label form-check-label"
+                htmlFor="bindByUserName-SAML"
+                dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical') }}
+              />
+            </div>
+            <p className="form-text text-muted">
+              <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat username matching as identical_warn') }} />
+            </p>
+          </div>
+
+          <div className="row mb-5 ms-3">
+            <div className="form-check form-check-success">
+              <input
+                id="bindByEmail-SAML"
+                className="form-check-input"
+                type="checkbox"
+                checked={adminSamlSecurityContainer.state.isSameEmailTreatedAsIdenticalUser || false}
+                onChange={() => { adminSamlSecurityContainer.switchIsSameEmailTreatedAsIdenticalUser() }}
+              />
+              <label
+                className="form-label form-check-label"
+                htmlFor="bindByEmail-SAML"
+                dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical') }}
+              />
+            </div>
+            <p className="form-text text-muted">
+              <small dangerouslySetInnerHTML={{ __html: t('security_settings.Treat email matching as identical_warn') }} />
+            </p>
+          </div>
+
+          <h3 className="alert-anchor border-bottom mb-4">
+            Attribute-based Login Control
+          </h3>
+
+          <p className="form-text text-muted">
+            <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_detail') }} />
+          </p>
+
+          <table className="table settings-table">
+            <colgroup>
+              <col className="item-name" />
+              <col className="from-db" />
+              <col className="from-env-vars" />
+            </colgroup>
+            <thead>
+              <tr><th></th><th>Database</th><th>Environment variables</th></tr>
+            </thead>
+            <tbody>
+              <tr>
+                <th>
+                  { t('security_settings.form_item_name.ABLCRule') }
+                </th>
+                <td>
+                  <textarea
+                    className="form-control"
+                    {...register('samlABLCRule')}
+                  />
+                  <div className="mt-2">
+                    <p>
+                      See&nbsp;
+                      <a
+                        href="https://lucene.apache.org/core/2_9_4/queryparsersyntax.html"
+                        target="_blank"
+                        rel="noreferer noreferrer"
+                      >
+                        Apache Lucene - Query Parser Syntax <span className="growi-custom-icons">external_link</span>
+                      </a>.
+                    </p>
+                    <div className="accordion" id="accordionId">
+                      <div className="accordion-item p-1">
+                        <h2 className="accordion-header">
+                          <button
+                            className="btn btn-link text-start"
+                            type="button"
+                            onClick={() => setIsHelpOpened(!isHelpOpened)}
+                            aria-expanded="true"
+                            aria-controls="ablchelp"
+                          >
+                            <span className="material-symbols-outlined me-1">
+                              {isHelpOpened ? 'expand_more' : 'chevron_right'}
+                            </span> Show more...
+                          </button>
+                        </h2>
+                        <Collapse isOpen={isHelpOpened}>
+                          <div className="accordion-body">
+                            <p dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_rule_help') }} />
+                            <p dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_rule_example1') }} />
+                            <p dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.attr_based_login_control_rule_example2') }} />
+                          </div>
+                        </Collapse>
+                      </div>
+                    </div>
+                  </div>
+                </td>
+                <td>
+                  <textarea
+                    className="form-control"
+                    value={adminSamlSecurityContainer.state.envABLCRule || ''}
+                    readOnly
+                  />
+                  <p className="form-text text-muted">
+                    <small dangerouslySetInnerHTML={{ __html: t('security_settings.SAML.Use env var if empty', { env: 'SAML_ABLC_RULE' }) }} />
+                  </p>
+                </td>
+              </tr>
+            </tbody>
+          </table>
+
+          <div className="row my-3">
+            <div className="offset-3 col-5">
+              <button
+                type="submit"
+                className="btn btn-primary"
+                disabled={adminSamlSecurityContainer.state.retrieveError != null}
+              >
+                {t('Update')}
+              </button>
+            </div>
+          </div>
+
+        </form>
+      )}
+
+    </React.Fragment>
+  );
+};
+
+const SamlSecurityManagementContentsWrapper = withUnstatedContainers(SamlSecurityManagementContents, [
+  AdminGeneralSecurityContainer,
+  AdminSamlSecurityContainer,
+]);
+
+export default SamlSecurityManagementContentsWrapper;

+ 1 - 1
apps/app/src/client/components/Admin/Security/SecurityManagementContents.jsx

@@ -12,7 +12,7 @@ import LdapSecuritySetting from './LdapSecuritySetting';
 import LocalSecuritySetting from './LocalSecuritySetting';
 import OidcSecuritySetting from './OidcSecuritySetting';
 import SamlSecuritySetting from './SamlSecuritySetting';
-import SecuritySetting from './SecuritySetting';
+import { SecuritySetting } from './SecuritySetting';
 import ShareLinkSetting from './ShareLinkSetting';
 
 const SecurityManagementContents = () => {

+ 0 - 635
apps/app/src/client/components/Admin/Security/SecuritySetting.jsx

@@ -1,635 +0,0 @@
-/* eslint-disable react/no-danger */
-import React from 'react';
-
-import { useTranslation } from 'next-i18next';
-import PropTypes from 'prop-types';
-import { Collapse } from 'reactstrap';
-
-import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
-import { toastSuccess, toastError } from '~/client/util/toastr';
-import { PageDeleteConfigValue } from '~/interfaces/page-delete-config';
-import { validateDeleteConfigs, prepareDeleteConfigValuesForCalc } from '~/utils/page-delete-config';
-
-import { withUnstatedContainers } from '../../UnstatedUtils';
-
-// used as the prefix of translation
-const DeletionTypeForT = Object.freeze({
-  Deletion: 'deletion',
-  CompleteDeletion: 'complete_deletion',
-  RecursiveDeletion: 'recursive_deletion',
-  RecursiveCompleteDeletion: 'recursive_complete_deletion',
-});
-
-const DeletionType = Object.freeze({
-  Deletion: 'deletion',
-  CompleteDeletion: 'completeDeletion',
-  RecursiveDeletion: 'recursiveDeletion',
-  RecursiveCompleteDeletion: 'recursiveCompleteDeletion',
-});
-
-const getDeletionTypeForT = (deletionType) => {
-  switch (deletionType) {
-    case DeletionType.Deletion:
-      return DeletionTypeForT.Deletion;
-    case DeletionType.RecursiveDeletion:
-      return DeletionTypeForT.RecursiveDeletion;
-    case DeletionType.CompleteDeletion:
-      return DeletionTypeForT.CompleteDeletion;
-    case DeletionType.RecursiveCompleteDeletion:
-      return DeletionTypeForT.RecursiveCompleteDeletion;
-  }
-};
-
-const getDeleteConfigValueForT = (DeleteConfigValue) => {
-  switch (DeleteConfigValue) {
-    case PageDeleteConfigValue.Anyone:
-    case null:
-      return 'security_settings.anyone';
-    case PageDeleteConfigValue.Inherit:
-      return 'security_settings.inherit';
-    case PageDeleteConfigValue.AdminOnly:
-      return 'security_settings.admin_only';
-    case PageDeleteConfigValue.AdminAndAuthor:
-      return 'security_settings.admin_and_author';
-  }
-};
-
-/**
- * Return true if "deletionType" is DeletionType.RecursiveDeletion or DeletionType.RecursiveCompleteDeletion.
- * @param deletionType Deletion type
- * @returns boolean
- */
-const isRecursiveDeletion = (deletionType) => {
-  return deletionType === DeletionType.RecursiveDeletion || deletionType === DeletionType.RecursiveCompleteDeletion;
-};
-
-/**
- * Return true if "deletionType" is DeletionType.Deletion or DeletionType.RecursiveDeletion.
- * @param deletionType Deletion type
- * @returns boolean
- */
-const isTypeDeletion = (deletionType) => {
-  return deletionType === DeletionType.Deletion || deletionType === DeletionType.RecursiveDeletion;
-};
-
-class SecuritySetting extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    // functions
-    this.putSecuritySetting = this.putSecuritySetting.bind(this);
-    this.getRecursiveDeletionConfigState = this.getRecursiveDeletionConfigState.bind(this);
-    this.previousPageRecursiveAuthorityState = this.previousPageRecursiveAuthorityState.bind(this);
-    this.setPagePreviousRecursiveAuthorityState = this.setPagePreviousRecursiveAuthorityState.bind(this);
-    this.expantDeleteOptionsState = this.expantDeleteOptionsState.bind(this);
-    this.setExpantOtherDeleteOptionsState = this.setExpantOtherDeleteOptionsState.bind(this);
-    this.setDeletionConfigState = this.setDeletionConfigState.bind(this);
-
-    // render
-    this.renderPageDeletePermission = this.renderPageDeletePermission.bind(this);
-    this.renderPageDeletePermissionDropdown = this.renderPageDeletePermissionDropdown.bind(this);
-  }
-
-  async putSecuritySetting() {
-    const { t, adminGeneralSecurityContainer } = this.props;
-    try {
-      await adminGeneralSecurityContainer.updateGeneralSecuritySetting();
-      toastSuccess(t('security_settings.updated_general_security_setting'));
-    }
-    catch (err) {
-      toastError(err);
-    }
-  }
-
-  getRecursiveDeletionConfigState(deletionType) {
-    const { adminGeneralSecurityContainer } = this.props;
-
-    if (isTypeDeletion(deletionType)) {
-      return [
-        adminGeneralSecurityContainer.state.currentPageRecursiveDeletionAuthority,
-        adminGeneralSecurityContainer.changePageRecursiveDeletionAuthority,
-      ];
-    }
-
-    return [
-      adminGeneralSecurityContainer.state.currentPageRecursiveCompleteDeletionAuthority,
-      adminGeneralSecurityContainer.changePageRecursiveCompleteDeletionAuthority,
-    ];
-  }
-
-  previousPageRecursiveAuthorityState(deletionType) {
-    const { adminGeneralSecurityContainer } = this.props;
-
-    return isTypeDeletion(deletionType)
-      ? adminGeneralSecurityContainer.state.previousPageRecursiveDeletionAuthority
-      : adminGeneralSecurityContainer.state.previousPageRecursiveCompleteDeletionAuthority;
-  }
-
-  setPagePreviousRecursiveAuthorityState(deletionType, previousState) {
-    const { adminGeneralSecurityContainer } = this.props;
-
-    if (isTypeDeletion(deletionType)) {
-      adminGeneralSecurityContainer.changePreviousPageRecursiveDeletionAuthority(previousState);
-      return;
-    }
-
-    adminGeneralSecurityContainer.changePreviousPageRecursiveCompleteDeletionAuthority(previousState);
-  }
-
-  expantDeleteOptionsState(deletionType) {
-    const { adminGeneralSecurityContainer } = this.props;
-
-    return isTypeDeletion(deletionType)
-      ? adminGeneralSecurityContainer.state.expandOtherOptionsForDeletion
-      : adminGeneralSecurityContainer.state.expandOtherOptionsForCompleteDeletion;
-  }
-
-  setExpantOtherDeleteOptionsState(deletionType, bool) {
-    const { adminGeneralSecurityContainer } = this.props;
-
-    if (isTypeDeletion(deletionType)) {
-      adminGeneralSecurityContainer.switchExpandOtherOptionsForDeletion(bool);
-      return;
-    }
-    adminGeneralSecurityContainer.switchExpandOtherOptionsForCompleteDeletion(bool);
-    return;
-  }
-
-  /**
-   * Force update deletion config for recursive operation when the deletion config for general operation is updated.
-   * @param deletionType Deletion type
-   */
-  setDeletionConfigState(newState, setState, deletionType) {
-    setState(newState);
-
-    if (this.previousPageRecursiveAuthorityState(deletionType) !== null) {
-      this.setPagePreviousRecursiveAuthorityState(deletionType, null);
-    }
-
-    if (isRecursiveDeletion(deletionType)) {
-      return;
-    }
-
-    const [recursiveState, setRecursiveState] = this.getRecursiveDeletionConfigState(deletionType);
-
-    const calculableValue = prepareDeleteConfigValuesForCalc(newState, recursiveState);
-    const shouldForceUpdate = !validateDeleteConfigs(calculableValue[0], calculableValue[1]);
-    if (shouldForceUpdate) {
-      setRecursiveState(newState);
-      this.setPagePreviousRecursiveAuthorityState(deletionType, recursiveState);
-      this.setExpantOtherDeleteOptionsState(deletionType, true);
-    }
-
-    return;
-  }
-
-  renderPageDeletePermissionDropdown(currentState, setState, deletionType, isButtonDisabled) {
-    const { t } = this.props;
-    return (
-      <div className="dropdown">
-        <button
-          className="btn btn-outline-secondary dropdown-toggle text-end"
-          type="button"
-          id="dropdownMenuButton"
-          data-bs-toggle="dropdown"
-          aria-haspopup="true"
-          aria-expanded="true"
-        >
-          <span className="float-start">
-            {t(getDeleteConfigValueForT(currentState))}
-          </span>
-        </button>
-        <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
-          {
-            isRecursiveDeletion(deletionType)
-              ? (
-                <button
-                  className="dropdown-item"
-                  type="button"
-                  onClick={() => { this.setDeletionConfigState(PageDeleteConfigValue.Inherit, setState, deletionType) }}
-                >
-                  {t('security_settings.inherit')}
-                </button>
-              )
-              : (
-                <button
-                  className="dropdown-item"
-                  type="button"
-                  onClick={() => { this.setDeletionConfigState(PageDeleteConfigValue.Anyone, setState, deletionType) }}
-                >
-                  {t('security_settings.anyone')}
-                </button>
-              )
-          }
-          <button
-            className={`dropdown-item ${isButtonDisabled ? 'disabled' : ''}`}
-            type="button"
-            onClick={() => { this.setDeletionConfigState(PageDeleteConfigValue.AdminAndAuthor, setState, deletionType) }}
-          >
-            {t('security_settings.admin_and_author')}
-          </button>
-          <button
-            className="dropdown-item"
-            type="button"
-            onClick={() => { this.setDeletionConfigState(PageDeleteConfigValue.AdminOnly, setState, deletionType) }}
-          >
-            {t('security_settings.admin_only')}
-          </button>
-        </div>
-        <p className="form-text text-muted small">
-          {t(`security_settings.${getDeletionTypeForT(deletionType)}_explanation`)}
-        </p>
-      </div>
-    );
-  }
-
-  renderPageDeletePermission(currentState, setState, deletionType, isButtonDisabled) {
-    const { t, adminGeneralSecurityContainer } = this.props;
-
-    const expantDeleteOptionsState = this.expantDeleteOptionsState(deletionType);
-
-    return (
-      <div key={`page-delete-permission-dropdown-${deletionType}`} className="row">
-
-        <div className="col-md-4 text-md-end">
-          {!isRecursiveDeletion(deletionType) && isTypeDeletion(deletionType) && (
-            <strong>{t('security_settings.page_delete')}</strong>
-          )}
-          {!isRecursiveDeletion(deletionType) && !isTypeDeletion(deletionType) && (
-            <strong>{t('security_settings.page_delete_completely')}</strong>
-          )}
-        </div>
-
-        <div className="col-md-8">
-          {
-            !isRecursiveDeletion(deletionType)
-              ? (
-                <>
-                  {this.renderPageDeletePermissionDropdown(currentState, setState, deletionType, isButtonDisabled)}
-                  {currentState === PageDeleteConfigValue.Anyone && deletionType === DeletionType.CompleteDeletion && (
-                    <>
-                      <input
-                        id="isAllGroupMembershipRequiredForPageCompleteDeletionCheckbox"
-                        className="form-check-input"
-                        type="checkbox"
-                        checked={adminGeneralSecurityContainer.state.isAllGroupMembershipRequiredForPageCompleteDeletion}
-                        onChange={() => { adminGeneralSecurityContainer.switchIsAllGroupMembershipRequiredForPageCompleteDeletion() }}
-                      />
-                      <label className="form-check-label" htmlFor="isAllGroupMembershipRequiredForPageCompleteDeletionCheckbox">
-                        {t('security_settings.is_all_group_membership_required_for_page_complete_deletion')}
-                      </label>
-                      <p
-                        className="form-text text-muted small mt-2"
-                      >
-                        {t('security_settings.is_all_group_membership_required_for_page_complete_deletion_explanation')}
-                      </p>
-                    </>
-                  )}
-                </>
-              )
-              : (
-                <>
-                  <button
-                    type="button"
-                    className="btn btn-link p-0 mb-4"
-                    aria-expanded="false"
-                    onClick={() => this.setExpantOtherDeleteOptionsState(deletionType, !expantDeleteOptionsState)}
-                  >
-                    <span className={`material-symbols-outlined me-1 ${expantDeleteOptionsState ? 'rotate-90' : ''}`}>navigate_next</span>
-                    {t('security_settings.other_options')}
-                  </button>
-                  <Collapse isOpen={expantDeleteOptionsState}>
-                    <div className="pb-4">
-                      <p className="card custom-card bg-warning-sublte">
-                        <span className="text-warning">
-                          <span className="material-symbols-outlined">info</span>
-                          {/* eslint-disable-next-line react/no-danger */}
-                          <span dangerouslySetInnerHTML={{ __html: t('security_settings.page_delete_rights_caution') }} />
-                        </span>
-                      </p>
-                      {this.previousPageRecursiveAuthorityState(deletionType) !== null && (
-                        <div className="mb-3">
-                          <strong>
-                            {t('security_settings.forced_update_desc')}
-                          </strong>
-                          <code>
-                            {t(getDeleteConfigValueForT(this.previousPageRecursiveAuthorityState(deletionType)))}
-                          </code>
-                        </div>
-                      )}
-                      {this.renderPageDeletePermissionDropdown(currentState, setState, deletionType, isButtonDisabled)}
-                    </div>
-                  </Collapse>
-                </>
-              )
-          }
-        </div>
-      </div>
-    );
-  }
-
-  render() {
-    const { t, adminGeneralSecurityContainer } = this.props;
-    const {
-      currentRestrictGuestMode, currentPageDeletionAuthority, currentPageCompleteDeletionAuthority,
-      currentPageRecursiveDeletionAuthority, currentPageRecursiveCompleteDeletionAuthority, isRomUserAllowedToComment,
-    } = adminGeneralSecurityContainer.state;
-
-    const isButtonDisabledForDeletion = !validateDeleteConfigs(
-      adminGeneralSecurityContainer.state.currentPageDeletionAuthority, PageDeleteConfigValue.AdminAndAuthor,
-    );
-
-    const isButtonDisabledForCompleteDeletion = !validateDeleteConfigs(
-      adminGeneralSecurityContainer.state.currentPageCompleteDeletionAuthority, PageDeleteConfigValue.AdminAndAuthor,
-    );
-
-    return (
-      <React.Fragment>
-        <h2 className="alert-anchor border-bottom">
-          {t('security_settings.security_settings')}
-        </h2>
-
-        {adminGeneralSecurityContainer.retrieveError != null && (
-          <div className="alert alert-danger">
-            <p>{t('Error occurred')} : {adminGeneralSecurityContainer.retrieveError}</p>
-          </div>
-        )}
-
-        <h4 className="alert-anchor border-bottom mt-4">{t('security_settings.page_list_and_search_results')}</h4>
-        <div className="row mb-4">
-          <div className="col-md-10">
-            <div className="row">
-
-              {/* Left Column: Labels */}
-              <div className="col-5 d-flex flex-column align-items-end p-4">
-                <div className="fw-bold mb-4">{t('public')}</div>
-                <div className="fw-bold mb-4">{t('anyone_with_the_link')}</div>
-                <div className="fw-bold mb-4">{t('only_me')}</div>
-                <div className="fw-bold">{t('only_inside_the_group')}</div>
-              </div>
-
-              {/* Right Column: Content */}
-              <div className="col-7 d-flex flex-column align-items-start pt-4 pb-4">
-                <div className="mb-4 d-flex align-items-center">
-                  <span className="material-symbols-outlined text-success me-1"></span>
-                  {t('security_settings.always_displayed')}
-                </div>
-                <div className="mb-3 d-flex align-items-center">
-                  <span className="material-symbols-outlined text-danger me-1"></span>
-                  {t('security_settings.always_hidden')}
-                </div>
-
-                {/* Owner Restriction Dropdown */}
-                <div className="mb-3">
-                  <div className="dropdown">
-                    <button
-                      className="btn btn-outline-secondary dropdown-toggle text-end col-12 col-md-auto"
-                      type="button"
-                      id="isShowRestrictedByOwner"
-                      data-bs-toggle="dropdown"
-                      aria-haspopup="true"
-                      aria-expanded="true"
-                    >
-                      <span className="float-start">
-                        {adminGeneralSecurityContainer.state.currentOwnerRestrictionDisplayMode === 'Displayed' && t('security_settings.always_displayed')}
-                        {adminGeneralSecurityContainer.state.currentOwnerRestrictionDisplayMode === 'Hidden' && t('security_settings.always_hidden')}
-                      </span>
-                    </button>
-                    <div className="dropdown-menu" aria-labelledby="isShowRestrictedByOwner">
-                      <button
-                        className="dropdown-item"
-                        type="button"
-                        onClick={() => { adminGeneralSecurityContainer.changeOwnerRestrictionDisplayMode('Displayed') }}
-                      >
-                        {t('security_settings.always_displayed')}
-                      </button>
-                      <button
-                        className="dropdown-item"
-                        type="button"
-                        onClick={() => { adminGeneralSecurityContainer.changeOwnerRestrictionDisplayMode('Hidden') }}
-                      >
-                        {t('security_settings.always_hidden')}
-                      </button>
-                    </div>
-                  </div>
-                </div>
-
-                {/* Group Restriction Dropdown */}
-                <div className="">
-                  <div className="dropdown">
-                    <button
-                      className="btn btn-outline-secondary dropdown-toggle text-end col-12 col-md-auto"
-                      type="button"
-                      id="isShowRestrictedByGroup"
-                      data-bs-toggle="dropdown"
-                      aria-haspopup="true"
-                      aria-expanded="true"
-                    >
-                      <span className="float-start">
-                        {adminGeneralSecurityContainer.state.currentGroupRestrictionDisplayMode === 'Displayed' && t('security_settings.always_displayed')}
-                        {adminGeneralSecurityContainer.state.currentGroupRestrictionDisplayMode === 'Hidden' && t('security_settings.always_hidden')}
-                      </span>
-                    </button>
-                    <div className="dropdown-menu" aria-labelledby="isShowRestrictedByGroup">
-                      <button
-                        className="dropdown-item"
-                        type="button"
-                        onClick={() => { adminGeneralSecurityContainer.changeGroupRestrictionDisplayMode('Displayed') }}
-                      >
-                        {t('security_settings.always_displayed')}
-                      </button>
-                      <button
-                        className="dropdown-item"
-                        type="button"
-                        onClick={() => { adminGeneralSecurityContainer.changeGroupRestrictionDisplayMode('Hidden') }}
-                      >
-                        {t('security_settings.always_hidden')}
-                      </button>
-                    </div>
-                  </div>
-                </div>
-              </div>
-            </div>
-          </div>
-        </div>
-
-        <h4 className="mb-3">{t('security_settings.page_access_rights')}</h4>
-        <div className="row mb-4">
-          <div className="col-md-4 text-md-end py-2">
-            <strong>{t('security_settings.Guest Users Access')}</strong>
-          </div>
-          <div className="col-md-8">
-            <div className="dropdown">
-              <button
-                className={`btn btn-outline-secondary dropdown-toggle text-end col-12
-                            col-md-auto ${adminGeneralSecurityContainer.isWikiModeForced && 'disabled'}`}
-                type="button"
-                id="dropdownMenuButton"
-                data-bs-toggle="dropdown"
-                aria-haspopup="true"
-                aria-expanded="true"
-              >
-                <span className="float-start">
-                  {currentRestrictGuestMode === 'Deny' && t('security_settings.guest_mode.deny')}
-                  {currentRestrictGuestMode === 'Readonly' && t('security_settings.guest_mode.readonly')}
-                </span>
-              </button>
-              <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
-                <button className="dropdown-item" type="button" onClick={() => { adminGeneralSecurityContainer.changeRestrictGuestMode('Deny') }}>
-                  {t('security_settings.guest_mode.deny')}
-                </button>
-                <button className="dropdown-item" type="button" onClick={() => { adminGeneralSecurityContainer.changeRestrictGuestMode('Readonly') }}>
-                  {t('security_settings.guest_mode.readonly')}
-                </button>
-              </div>
-            </div>
-            {adminGeneralSecurityContainer.isWikiModeForced && (
-              <p className="alert alert-warning mt-2 col-6">
-                <span className="material-symbols-outlined me-1">error</span>
-                <b>FIXED</b><br />
-                <b
-                  dangerouslySetInnerHTML={{
-                    __html: t('security_settings.Fixed by env var',
-                      { key: 'FORCE_WIKI_MODE', value: adminGeneralSecurityContainer.state.wikiMode }),
-                  }}
-                />
-              </p>
-            )}
-          </div>
-        </div>
-
-        <h4 className="mb-3">{t('security_settings.page_delete_rights')}</h4>
-        {/* Render PageDeletePermission */}
-        {
-          [
-            [currentPageDeletionAuthority, adminGeneralSecurityContainer.changePageDeletionAuthority, DeletionType.Deletion, false],
-            // eslint-disable-next-line max-len
-            [currentPageRecursiveDeletionAuthority, adminGeneralSecurityContainer.changePageRecursiveDeletionAuthority, DeletionType.RecursiveDeletion, isButtonDisabledForDeletion],
-          ].map(arr => this.renderPageDeletePermission(arr[0], arr[1], arr[2], arr[3]))
-        }
-        {
-          [
-            [currentPageCompleteDeletionAuthority, adminGeneralSecurityContainer.changePageCompleteDeletionAuthority, DeletionType.CompleteDeletion, false],
-            // eslint-disable-next-line max-len
-            [currentPageRecursiveCompleteDeletionAuthority, adminGeneralSecurityContainer.changePageRecursiveCompleteDeletionAuthority, DeletionType.RecursiveCompleteDeletion, isButtonDisabledForCompleteDeletion],
-          ].map(arr => this.renderPageDeletePermission(arr[0], arr[1], arr[2], arr[3]))
-        }
-
-        <h4 className="mb-3">{t('security_settings.user_homepage_deletion.user_homepage_deletion')}</h4>
-        <div className="row mb-4">
-          <div className="col-md-10 offset-md-2">
-            <div className="form-check form-switch form-check-success">
-              <input
-                type="checkbox"
-                className="form-check-input"
-                id="is-user-page-deletion-enabled"
-                checked={adminGeneralSecurityContainer.state.isUsersHomepageDeletionEnabled}
-                onChange={() => { adminGeneralSecurityContainer.switchIsUsersHomepageDeletionEnabled() }}
-              />
-              <label className="form-label form-check-label" htmlFor="is-user-page-deletion-enabled">
-                {t('security_settings.user_homepage_deletion.enable_user_homepage_deletion')}
-              </label>
-            </div>
-            <div className="custom-control custom-switch custom-checkbox-success mt-2">
-              <input
-                type="checkbox"
-                className="form-check-input"
-                id="is-force-delete-user-homepage-on-user-deletion"
-                checked={adminGeneralSecurityContainer.state.isForceDeleteUserHomepageOnUserDeletion}
-                onChange={() => { adminGeneralSecurityContainer.switchIsForceDeleteUserHomepageOnUserDeletion() }}
-                disabled={!adminGeneralSecurityContainer.state.isUsersHomepageDeletionEnabled}
-              />
-              <label className="form-check-label" htmlFor="is-force-delete-user-homepage-on-user-deletion">
-                {t('security_settings.user_homepage_deletion.enable_force_delete_user_homepage_on_user_deletion')}
-              </label>
-            </div>
-            <p
-              className="form-text text-muted small mt-2"
-              dangerouslySetInnerHTML={{ __html: t('security_settings.user_homepage_deletion.desc') }}
-            />
-          </div>
-        </div>
-
-        <h4 className="mb-3">{t('security_settings.comment_manage_rights')}</h4>
-        <div className="row mb-4">
-          <div className="col-md-4 text-md-end py-2">
-            <strong>{t('security_settings.readonly_users_access')}</strong>
-          </div>
-          <div className="col-md-8">
-            <div className="dropdown">
-              <button
-                className={`btn btn-outline-secondary dropdown-toggle text-end col-12
-                            col-md-auto ${adminGeneralSecurityContainer.isWikiModeForced && 'disabled'}`}
-                type="button"
-                id="dropdownMenuButton"
-                data-bs-toggle="dropdown"
-                aria-haspopup="true"
-                aria-expanded="true"
-              >
-                <span className="float-start">
-                  {isRomUserAllowedToComment === true && t('security_settings.read_only_users_comment.accept')}
-                  {isRomUserAllowedToComment === false && t('security_settings.read_only_users_comment.deny')}
-                </span>
-              </button>
-              <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
-                <button className="dropdown-item" type="button" onClick={() => { adminGeneralSecurityContainer.switchIsRomUserAllowedToComment(false) }}>
-                  {t('security_settings.read_only_users_comment.deny')}
-                </button>
-                <button className="dropdown-item" type="button" onClick={() => { adminGeneralSecurityContainer.switchIsRomUserAllowedToComment(true) }}>
-                  {t('security_settings.read_only_users_comment.accept')}
-                </button>
-              </div>
-            </div>
-          </div>
-        </div>
-
-        <h4>{t('security_settings.session')}</h4>
-        <div className="row">
-          <label className="text-start text-md-end col-md-3 col-form-label">{t('security_settings.max_age')}</label>
-          <div className="col-md-8">
-            <input
-              className="form-control col-md-4"
-              type="text"
-              value={adminGeneralSecurityContainer.state.sessionMaxAge || ''}
-              onChange={(e) => {
-                adminGeneralSecurityContainer.setSessionMaxAge(e.target.value);
-              }}
-              placeholder="2592000000"
-            />
-            {/* eslint-disable-next-line react/no-danger */}
-            <p className="form-text text-muted" dangerouslySetInnerHTML={{ __html: t('security_settings.max_age_desc') }} />
-            <p className="card custom-card bg-warning-subtle">
-              <span className="text-warning">
-                <span className="material-symbols-outlined">info</span> {t('security_settings.max_age_caution')}
-              </span>
-            </p>
-          </div>
-        </div>
-
-        <div className="row my-3">
-          <div className="text-center text-md-start offset-md-3 col-md-5">
-            <button type="button" className="btn btn-primary" disabled={adminGeneralSecurityContainer.retrieveError != null} onClick={this.putSecuritySetting}>
-              {t('Update')}
-            </button>
-          </div>
-        </div>
-      </React.Fragment>
-    );
-  }
-
-}
-
-SecuritySetting.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
-};
-
-const SecuritySettingWrapperFC = (props) => {
-  const { t } = useTranslation('admin');
-  return <SecuritySetting t={t} {...props} />;
-};
-
-const SecuritySettingWrapper = withUnstatedContainers(SecuritySettingWrapperFC, [AdminGeneralSecurityContainer]);
-
-export default SecuritySettingWrapper;

+ 58 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/CommentManageRightsSettings.tsx

@@ -0,0 +1,58 @@
+import React from 'react';
+
+import type AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  t: (key: string) => string;
+};
+
+export const CommentManageRightsSettings: React.FC<Props> = ({ adminGeneralSecurityContainer, t }) => {
+  const { isRomUserAllowedToComment } = adminGeneralSecurityContainer.state;
+
+  return (
+    <>
+      <h4 className="mb-3">{t('security_settings.comment_manage_rights')}</h4>
+      <div className="row mb-4">
+        <div className="col-md-4 text-md-end py-2">
+          <strong>{t('security_settings.readonly_users_access')}</strong>
+        </div>
+        <div className="col-md-8">
+          <div className="dropdown">
+            <button
+              className={`btn btn-outline-secondary dropdown-toggle text-end col-12 col-md-auto ${
+                adminGeneralSecurityContainer.isWikiModeForced && 'disabled'
+              }`}
+              type="button"
+              id="dropdownMenuButton"
+              data-bs-toggle="dropdown"
+              aria-haspopup="true"
+              aria-expanded="true"
+            >
+              <span className="float-start">
+                {isRomUserAllowedToComment === true && t('security_settings.read_only_users_comment.accept')}
+                {isRomUserAllowedToComment === false && t('security_settings.read_only_users_comment.deny')}
+              </span>
+            </button>
+            <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
+              <button
+                className="dropdown-item"
+                type="button"
+                onClick={() => { adminGeneralSecurityContainer.switchIsRomUserAllowedToComment(false) }}
+              >
+                {t('security_settings.read_only_users_comment.deny')}
+              </button>
+              <button
+                className="dropdown-item"
+                type="button"
+                onClick={() => { adminGeneralSecurityContainer.switchIsRomUserAllowedToComment(true) }}
+              >
+                {t('security_settings.read_only_users_comment.accept')}
+              </button>
+            </div>
+          </div>
+        </div>
+      </div>
+    </>
+  );
+};

+ 75 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/PageAccessRightsSettings.tsx

@@ -0,0 +1,75 @@
+/* eslint-disable react/no-danger */
+import React from 'react';
+
+import type AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  t: (key: string, options?: Record<string, unknown>) => string;
+};
+
+export const PageAccessRightsSettings: React.FC<Props> = ({ adminGeneralSecurityContainer, t }) => {
+  const { currentRestrictGuestMode } = adminGeneralSecurityContainer.state;
+
+  return (
+    <>
+      <h4 className="mb-3">{t('security_settings.page_access_rights')}</h4>
+      <div className="row mb-4">
+        <div className="col-md-4 text-md-end py-2">
+          <strong>{t('security_settings.Guest Users Access')}</strong>
+        </div>
+        <div className="col-md-8">
+          <div className="dropdown">
+            <button
+              className={`btn btn-outline-secondary dropdown-toggle text-end col-12 col-md-auto ${
+                adminGeneralSecurityContainer.isWikiModeForced && 'disabled'
+              }`}
+              type="button"
+              id="dropdownMenuButton"
+              data-bs-toggle="dropdown"
+              aria-haspopup="true"
+              aria-expanded="true"
+            >
+              <span className="float-start">
+                {currentRestrictGuestMode === 'Deny' && t('security_settings.guest_mode.deny')}
+                {currentRestrictGuestMode === 'Readonly' && t('security_settings.guest_mode.readonly')}
+              </span>
+            </button>
+            <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
+              <button
+                className="dropdown-item"
+                type="button"
+                onClick={() => { adminGeneralSecurityContainer.changeRestrictGuestMode('Deny') }}
+              >
+                {t('security_settings.guest_mode.deny')}
+              </button>
+              <button
+                className="dropdown-item"
+                type="button"
+                onClick={() => { adminGeneralSecurityContainer.changeRestrictGuestMode('Readonly') }}
+              >
+                {t('security_settings.guest_mode.readonly')}
+              </button>
+            </div>
+          </div>
+          {adminGeneralSecurityContainer.isWikiModeForced && (
+            <p className="alert alert-warning mt-2 col-6">
+              <span className="material-symbols-outlined me-1">error</span>
+              <b>FIXED</b>
+              <br />
+              {/* eslint-disable-next-line react/no-danger */}
+              <b
+                dangerouslySetInnerHTML={{
+                  __html: t('security_settings.Fixed by env var', {
+                    key: 'FORCE_WIKI_MODE',
+                    value: adminGeneralSecurityContainer.state.wikiMode,
+                  }),
+                }}
+              />
+            </p>
+          )}
+        </div>
+      </div>
+    </>
+  );
+};

+ 289 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/PageDeleteRightsSettings.tsx

@@ -0,0 +1,289 @@
+import React, { useCallback } from 'react';
+
+import { Collapse } from 'reactstrap';
+
+import type AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+import {
+  PageDeleteConfigValue,
+  type IPageDeleteConfigValue,
+  type IPageDeleteConfigValueToProcessValidation,
+} from '~/interfaces/page-delete-config';
+import { validateDeleteConfigs, prepareDeleteConfigValuesForCalc } from '~/utils/page-delete-config';
+
+import {
+  DeletionType,
+  type DeletionTypeValue,
+  getDeletionTypeForT,
+  getDeleteConfigValueForT,
+  isRecursiveDeletion,
+  isTypeDeletion,
+} from './types';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  t: (key: string) => string;
+};
+
+export const PageDeleteRightsSettings: React.FC<Props> = ({ adminGeneralSecurityContainer, t }) => {
+  const {
+    currentPageDeletionAuthority,
+    currentPageCompleteDeletionAuthority,
+    currentPageRecursiveDeletionAuthority,
+    currentPageRecursiveCompleteDeletionAuthority,
+  } = adminGeneralSecurityContainer.state;
+
+  const getRecursiveDeletionConfigState = useCallback((deletionType: DeletionTypeValue) => {
+    if (isTypeDeletion(deletionType)) {
+      return [
+        adminGeneralSecurityContainer.state.currentPageRecursiveDeletionAuthority,
+        adminGeneralSecurityContainer.changePageRecursiveDeletionAuthority,
+      ] as const;
+    }
+
+    return [
+      adminGeneralSecurityContainer.state.currentPageRecursiveCompleteDeletionAuthority,
+      adminGeneralSecurityContainer.changePageRecursiveCompleteDeletionAuthority,
+    ] as const;
+  }, [adminGeneralSecurityContainer]);
+
+  const previousPageRecursiveAuthorityState = useCallback((deletionType: DeletionTypeValue) => {
+    return isTypeDeletion(deletionType)
+      ? adminGeneralSecurityContainer.state.previousPageRecursiveDeletionAuthority
+      : adminGeneralSecurityContainer.state.previousPageRecursiveCompleteDeletionAuthority;
+  }, [adminGeneralSecurityContainer]);
+
+  const setPagePreviousRecursiveAuthorityState = useCallback((deletionType: DeletionTypeValue, previousState: IPageDeleteConfigValue | null) => {
+    if (isTypeDeletion(deletionType)) {
+      adminGeneralSecurityContainer.changePreviousPageRecursiveDeletionAuthority(previousState);
+      return;
+    }
+
+    adminGeneralSecurityContainer.changePreviousPageRecursiveCompleteDeletionAuthority(previousState);
+  }, [adminGeneralSecurityContainer]);
+
+  const expandDeleteOptionsState = useCallback((deletionType: DeletionTypeValue) => {
+    return isTypeDeletion(deletionType)
+      ? adminGeneralSecurityContainer.state.expandOtherOptionsForDeletion
+      : adminGeneralSecurityContainer.state.expandOtherOptionsForCompleteDeletion;
+  }, [adminGeneralSecurityContainer]);
+
+  const setExpandOtherDeleteOptionsState = useCallback((deletionType: DeletionTypeValue, bool: boolean) => {
+    if (isTypeDeletion(deletionType)) {
+      adminGeneralSecurityContainer.switchExpandOtherOptionsForDeletion(bool);
+      return;
+    }
+    adminGeneralSecurityContainer.switchExpandOtherOptionsForCompleteDeletion(bool);
+  }, [adminGeneralSecurityContainer]);
+
+  const setDeletionConfigState = useCallback((
+      newState: IPageDeleteConfigValue,
+      setState: (value: IPageDeleteConfigValue) => void,
+      deletionType: DeletionTypeValue,
+  ) => {
+    setState(newState);
+
+    if (previousPageRecursiveAuthorityState(deletionType) !== null) {
+      setPagePreviousRecursiveAuthorityState(deletionType, null);
+    }
+
+    if (isRecursiveDeletion(deletionType)) {
+      return;
+    }
+
+    const [recursiveState, setRecursiveState] = getRecursiveDeletionConfigState(deletionType);
+
+    const calculableValue = prepareDeleteConfigValuesForCalc(
+      newState as IPageDeleteConfigValueToProcessValidation,
+      recursiveState as IPageDeleteConfigValueToProcessValidation,
+    );
+    const shouldForceUpdate = !validateDeleteConfigs(calculableValue[0], calculableValue[1]);
+    if (shouldForceUpdate) {
+      setRecursiveState(newState);
+      setPagePreviousRecursiveAuthorityState(deletionType, recursiveState);
+      setExpandOtherDeleteOptionsState(deletionType, true);
+    }
+  }, [
+    getRecursiveDeletionConfigState,
+    previousPageRecursiveAuthorityState,
+    setPagePreviousRecursiveAuthorityState,
+    setExpandOtherDeleteOptionsState,
+  ]);
+
+  const renderPageDeletePermissionDropdown = useCallback((
+      currentState: IPageDeleteConfigValue,
+      setState: (value: IPageDeleteConfigValue) => void,
+      deletionType: DeletionTypeValue,
+      isButtonDisabled: boolean,
+  ) => {
+    return (
+      <div className="dropdown">
+        <button
+          className="btn btn-outline-secondary dropdown-toggle text-end"
+          type="button"
+          id="dropdownMenuButton"
+          data-bs-toggle="dropdown"
+          aria-haspopup="true"
+          aria-expanded="true"
+        >
+          <span className="float-start">{t(getDeleteConfigValueForT(currentState))}</span>
+        </button>
+        <div className="dropdown-menu" aria-labelledby="dropdownMenuButton">
+          {isRecursiveDeletion(deletionType)
+            ? (
+              <button
+                className="dropdown-item"
+                type="button"
+                onClick={() => { setDeletionConfigState(PageDeleteConfigValue.Inherit, setState, deletionType) }}
+              >
+                {t('security_settings.inherit')}
+              </button>
+            )
+            : (
+              <button
+                className="dropdown-item"
+                type="button"
+                onClick={() => { setDeletionConfigState(PageDeleteConfigValue.Anyone, setState, deletionType) }}
+              >
+                {t('security_settings.anyone')}
+              </button>
+            )}
+          <button
+            className={`dropdown-item ${isButtonDisabled ? 'disabled' : ''}`}
+            type="button"
+            onClick={() => { setDeletionConfigState(PageDeleteConfigValue.AdminAndAuthor, setState, deletionType) }}
+          >
+            {t('security_settings.admin_and_author')}
+          </button>
+          <button
+            className="dropdown-item"
+            type="button"
+            onClick={() => { setDeletionConfigState(PageDeleteConfigValue.AdminOnly, setState, deletionType) }}
+          >
+            {t('security_settings.admin_only')}
+          </button>
+        </div>
+        <p className="form-text text-muted small">{t(`security_settings.${getDeletionTypeForT(deletionType)}_explanation`)}</p>
+      </div>
+    );
+  }, [t, setDeletionConfigState]);
+
+  const renderPageDeletePermission = useCallback((
+      currentState: IPageDeleteConfigValue,
+      setState: (value: IPageDeleteConfigValue) => void,
+      deletionType: DeletionTypeValue,
+      isButtonDisabled: boolean,
+  ) => {
+    const expandDeleteOptions = expandDeleteOptionsState(deletionType);
+
+    return (
+      <div key={`page-delete-permission-dropdown-${deletionType}`} className="row">
+        <div className="col-md-4 text-md-end">
+          {!isRecursiveDeletion(deletionType) && isTypeDeletion(deletionType) && <strong>{t('security_settings.page_delete')}</strong>}
+          {!isRecursiveDeletion(deletionType) && !isTypeDeletion(deletionType) && <strong>{t('security_settings.page_delete_completely')}</strong>}
+        </div>
+
+        <div className="col-md-8">
+          {!isRecursiveDeletion(deletionType)
+            ? (
+              <>
+                {renderPageDeletePermissionDropdown(currentState, setState, deletionType, isButtonDisabled)}
+                {currentState === PageDeleteConfigValue.Anyone && deletionType === DeletionType.CompleteDeletion && (
+                  <>
+                    <input
+                      id="isAllGroupMembershipRequiredForPageCompleteDeletionCheckbox"
+                      className="form-check-input"
+                      type="checkbox"
+                      checked={adminGeneralSecurityContainer.state.isAllGroupMembershipRequiredForPageCompleteDeletion}
+                      onChange={() => { adminGeneralSecurityContainer.switchIsAllGroupMembershipRequiredForPageCompleteDeletion() }}
+                    />
+                    <label className="form-check-label" htmlFor="isAllGroupMembershipRequiredForPageCompleteDeletionCheckbox">
+                      {t('security_settings.is_all_group_membership_required_for_page_complete_deletion')}
+                    </label>
+                    <p className="form-text text-muted small mt-2">
+                      {t('security_settings.is_all_group_membership_required_for_page_complete_deletion_explanation')}
+                    </p>
+                  </>
+                )}
+              </>
+            )
+            : (
+              <>
+                <button
+                  type="button"
+                  className="btn btn-link p-0 mb-4"
+                  aria-expanded="false"
+                  onClick={() => setExpandOtherDeleteOptionsState(deletionType, !expandDeleteOptions)}
+                >
+                  <span className={`material-symbols-outlined me-1 ${expandDeleteOptions ? 'rotate-90' : ''}`}>navigate_next</span>
+                  {t('security_settings.other_options')}
+                </button>
+                <Collapse isOpen={expandDeleteOptions}>
+                  <div className="pb-4">
+                    <p className="card custom-card bg-warning-sublte">
+                      <span className="text-warning">
+                        <span className="material-symbols-outlined">info</span>
+                        {/* eslint-disable-next-line react/no-danger */}
+                        <span dangerouslySetInnerHTML={{ __html: t('security_settings.page_delete_rights_caution') }} />
+                      </span>
+                    </p>
+                    {previousPageRecursiveAuthorityState(deletionType) !== null && (
+                      <div className="mb-3">
+                        <strong>{t('security_settings.forced_update_desc')}</strong>
+                        <code>{t(getDeleteConfigValueForT(previousPageRecursiveAuthorityState(deletionType)))}</code>
+                      </div>
+                    )}
+                    {renderPageDeletePermissionDropdown(currentState, setState, deletionType, isButtonDisabled)}
+                  </div>
+                </Collapse>
+              </>
+            )}
+        </div>
+      </div>
+    );
+  }, [
+    adminGeneralSecurityContainer,
+    expandDeleteOptionsState,
+    previousPageRecursiveAuthorityState,
+    renderPageDeletePermissionDropdown,
+    setExpandOtherDeleteOptionsState,
+    t,
+  ]);
+
+  const isButtonDisabledForDeletion = !validateDeleteConfigs(currentPageDeletionAuthority, PageDeleteConfigValue.AdminAndAuthor);
+
+  const isButtonDisabledForCompleteDeletion = !validateDeleteConfigs(currentPageCompleteDeletionAuthority, PageDeleteConfigValue.AdminAndAuthor);
+
+  return (
+    <>
+      <h4 className="mb-3">{t('security_settings.page_delete_rights')}</h4>
+      {[
+        [currentPageDeletionAuthority, adminGeneralSecurityContainer.changePageDeletionAuthority, DeletionType.Deletion, false],
+        [
+          currentPageRecursiveDeletionAuthority,
+          adminGeneralSecurityContainer.changePageRecursiveDeletionAuthority,
+          DeletionType.RecursiveDeletion,
+          isButtonDisabledForDeletion,
+        ],
+      ].map(arr => renderPageDeletePermission(
+        arr[0] as IPageDeleteConfigValue,
+        arr[1] as (value: IPageDeleteConfigValue) => void,
+        arr[2] as DeletionTypeValue,
+        arr[3] as boolean,
+      ))}
+      {[
+        [currentPageCompleteDeletionAuthority, adminGeneralSecurityContainer.changePageCompleteDeletionAuthority, DeletionType.CompleteDeletion, false],
+        [
+          currentPageRecursiveCompleteDeletionAuthority,
+          adminGeneralSecurityContainer.changePageRecursiveCompleteDeletionAuthority,
+          DeletionType.RecursiveCompleteDeletion,
+          isButtonDisabledForCompleteDeletion,
+        ],
+      ].map(arr => renderPageDeletePermission(
+        arr[0] as IPageDeleteConfigValue,
+        arr[1] as (value: IPageDeleteConfigValue) => void,
+        arr[2] as DeletionTypeValue,
+        arr[3] as boolean,
+      ))}
+    </>
+  );
+};

+ 117 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/PageListDisplaySettings.tsx

@@ -0,0 +1,117 @@
+import React from 'react';
+
+import type AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  t: (key: string) => string;
+};
+
+export const PageListDisplaySettings: React.FC<Props> = ({ adminGeneralSecurityContainer, t }) => {
+  return (
+    <>
+      <h4 className="alert-anchor">
+        {t('security_settings.page_list_and_search_results')}
+      </h4>
+      <div className="row mb-4">
+        <div className="col-md-10">
+          <div className="row">
+            {/* Left Column: Labels */}
+            <div className="col-5 d-flex flex-column align-items-end p-4">
+              <div className="fw-bold mb-4">{t('public')}</div>
+              <div className="fw-bold mb-4">{t('anyone_with_the_link')}</div>
+              <div className="fw-bold mb-4">{t('only_me')}</div>
+              <div className="fw-bold">{t('only_inside_the_group')}</div>
+            </div>
+
+            {/* Right Column: Content */}
+            <div className="col-7 d-flex flex-column align-items-start pt-4 pb-4">
+              <div className="mb-4 d-flex align-items-center">
+                <span className="material-symbols-outlined text-success me-1"></span>
+                {t('security_settings.always_displayed')}
+              </div>
+              <div className="mb-3 d-flex align-items-center">
+                <span className="material-symbols-outlined text-danger me-1"></span>
+                {t('security_settings.always_hidden')}
+              </div>
+
+              {/* Owner Restriction Dropdown */}
+              <div className="mb-3">
+                <div className="dropdown">
+                  <button
+                    className="btn btn-outline-secondary dropdown-toggle text-end col-12 col-md-auto"
+                    type="button"
+                    id="isShowRestrictedByOwner"
+                    data-bs-toggle="dropdown"
+                    aria-haspopup="true"
+                    aria-expanded="true"
+                  >
+                    <span className="float-start">
+                      {adminGeneralSecurityContainer.state.currentOwnerRestrictionDisplayMode === 'Displayed'
+                        && t('security_settings.always_displayed')}
+                      {adminGeneralSecurityContainer.state.currentOwnerRestrictionDisplayMode === 'Hidden'
+                        && t('security_settings.always_hidden')}
+                    </span>
+                  </button>
+                  <div className="dropdown-menu" aria-labelledby="isShowRestrictedByOwner">
+                    <button
+                      className="dropdown-item"
+                      type="button"
+                      onClick={() => { adminGeneralSecurityContainer.changeOwnerRestrictionDisplayMode('Displayed') }}
+                    >
+                      {t('security_settings.always_displayed')}
+                    </button>
+                    <button
+                      className="dropdown-item"
+                      type="button"
+                      onClick={() => { adminGeneralSecurityContainer.changeOwnerRestrictionDisplayMode('Hidden') }}
+                    >
+                      {t('security_settings.always_hidden')}
+                    </button>
+                  </div>
+                </div>
+              </div>
+
+              {/* Group Restriction Dropdown */}
+              <div className="">
+                <div className="dropdown">
+                  <button
+                    className="btn btn-outline-secondary dropdown-toggle text-end col-12 col-md-auto"
+                    type="button"
+                    id="isShowRestrictedByGroup"
+                    data-bs-toggle="dropdown"
+                    aria-haspopup="true"
+                    aria-expanded="true"
+                  >
+                    <span className="float-start">
+                      {adminGeneralSecurityContainer.state.currentGroupRestrictionDisplayMode === 'Displayed'
+                        && t('security_settings.always_displayed')}
+                      {adminGeneralSecurityContainer.state.currentGroupRestrictionDisplayMode === 'Hidden'
+                        && t('security_settings.always_hidden')}
+                    </span>
+                  </button>
+                  <div className="dropdown-menu" aria-labelledby="isShowRestrictedByGroup">
+                    <button
+                      className="dropdown-item"
+                      type="button"
+                      onClick={() => { adminGeneralSecurityContainer.changeGroupRestrictionDisplayMode('Displayed') }}
+                    >
+                      {t('security_settings.always_displayed')}
+                    </button>
+                    <button
+                      className="dropdown-item"
+                      type="button"
+                      onClick={() => { adminGeneralSecurityContainer.changeGroupRestrictionDisplayMode('Hidden') }}
+                    >
+                      {t('security_settings.always_hidden')}
+                    </button>
+                  </div>
+                </div>
+              </div>
+            </div>
+          </div>
+        </div>
+      </div>
+    </>
+  );
+};

+ 36 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/SessionMaxAgeSettings.tsx

@@ -0,0 +1,36 @@
+import React from 'react';
+
+import type { UseFormRegister } from 'react-hook-form';
+
+type Props = {
+  register: UseFormRegister<{ sessionMaxAge: string }>;
+  t: (key: string, options?: Record<string, unknown>) => string;
+};
+
+export const SessionMaxAgeSettings: React.FC<Props> = ({ register, t }) => {
+  return (
+    <>
+      <h4>{t('security_settings.session')}</h4>
+      <div className="row">
+        <label className="text-start text-md-end col-md-3 col-form-label">
+          {t('security_settings.max_age')}
+        </label>
+        <div className="col-md-8">
+          <input
+            className="form-control col-md-4"
+            type="text"
+            {...register('sessionMaxAge')}
+            placeholder="2592000000"
+          />
+          {/* eslint-disable-next-line react/no-danger */}
+          <p className="form-text text-muted" dangerouslySetInnerHTML={{ __html: t('security_settings.max_age_desc') }} />
+          <p className="card custom-card bg-warning-subtle">
+            <span className="text-warning">
+              <span className="material-symbols-outlined">info</span> {t('security_settings.max_age_caution')}
+            </span>
+          </p>
+        </div>
+      </div>
+    </>
+  );
+};

+ 50 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/UserHomepageDeletionSettings.tsx

@@ -0,0 +1,50 @@
+/* eslint-disable react/no-danger */
+import React from 'react';
+
+import type AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+  t: (key: string) => string;
+};
+
+export const UserHomepageDeletionSettings: React.FC<Props> = ({ adminGeneralSecurityContainer, t }) => {
+  return (
+    <>
+      <h4 className="mb-3">{t('security_settings.user_homepage_deletion.user_homepage_deletion')}</h4>
+      <div className="row mb-4">
+        <div className="col-md-10 offset-md-2">
+          <div className="form-check form-switch form-check-success">
+            <input
+              type="checkbox"
+              className="form-check-input"
+              id="is-user-page-deletion-enabled"
+              checked={adminGeneralSecurityContainer.state.isUsersHomepageDeletionEnabled}
+              onChange={() => { adminGeneralSecurityContainer.switchIsUsersHomepageDeletionEnabled() }}
+            />
+            <label className="form-label form-check-label" htmlFor="is-user-page-deletion-enabled">
+              {t('security_settings.user_homepage_deletion.enable_user_homepage_deletion')}
+            </label>
+          </div>
+          <div className="custom-control custom-switch custom-checkbox-success mt-2">
+            <input
+              type="checkbox"
+              className="form-check-input"
+              id="is-force-delete-user-homepage-on-user-deletion"
+              checked={adminGeneralSecurityContainer.state.isForceDeleteUserHomepageOnUserDeletion}
+              onChange={() => { adminGeneralSecurityContainer.switchIsForceDeleteUserHomepageOnUserDeletion() }}
+              disabled={!adminGeneralSecurityContainer.state.isUsersHomepageDeletionEnabled}
+            />
+            <label className="form-check-label" htmlFor="is-force-delete-user-homepage-on-user-deletion">
+              {t('security_settings.user_homepage_deletion.enable_force_delete_user_homepage_on_user_deletion')}
+            </label>
+          </div>
+          <p
+            className="form-text text-muted small mt-2"
+            dangerouslySetInnerHTML={{ __html: t('security_settings.user_homepage_deletion.desc') }}
+          />
+        </div>
+      </div>
+    </>
+  );
+};

+ 88 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/index.tsx

@@ -0,0 +1,88 @@
+import React, { useCallback, useEffect } from 'react';
+
+import { useTranslation } from 'next-i18next';
+import { useForm } from 'react-hook-form';
+
+import AdminGeneralSecurityContainer from '~/client/services/AdminGeneralSecurityContainer';
+import { toastSuccess, toastError } from '~/client/util/toastr';
+
+import { withUnstatedContainers } from '../../../UnstatedUtils';
+
+import { CommentManageRightsSettings } from './CommentManageRightsSettings';
+import { PageAccessRightsSettings } from './PageAccessRightsSettings';
+import { PageDeleteRightsSettings } from './PageDeleteRightsSettings';
+import { PageListDisplaySettings } from './PageListDisplaySettings';
+import { SessionMaxAgeSettings } from './SessionMaxAgeSettings';
+import { UserHomepageDeletionSettings } from './UserHomepageDeletionSettings';
+
+type FormData = {
+  sessionMaxAge: string;
+};
+
+type Props = {
+  adminGeneralSecurityContainer: AdminGeneralSecurityContainer;
+};
+
+const SecuritySettingComponent: React.FC<Props> = ({ adminGeneralSecurityContainer }) => {
+  const { t } = useTranslation('admin');
+  const { register, handleSubmit, reset } = useForm<FormData>();
+
+  // Initialize form with current sessionMaxAge value
+  useEffect(() => {
+    reset({
+      sessionMaxAge: adminGeneralSecurityContainer.state.sessionMaxAge || '',
+    });
+  }, [reset, adminGeneralSecurityContainer.state.sessionMaxAge]);
+
+  const onSubmit = useCallback(async(data: FormData) => {
+    try {
+      // Update sessionMaxAge from form data
+      await adminGeneralSecurityContainer.setSessionMaxAge(data.sessionMaxAge);
+      // Save all security settings
+      await adminGeneralSecurityContainer.updateGeneralSecuritySetting();
+      toastSuccess(t('security_settings.updated_general_security_setting'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }, [adminGeneralSecurityContainer, t]);
+
+  if (adminGeneralSecurityContainer.state.retrieveError != null) {
+    return (
+      <div>
+        <p>
+          {t('Error occurred')} : {adminGeneralSecurityContainer.state.retrieveError}
+        </p>
+      </div>
+    );
+  }
+
+  return (
+    <div data-testid="admin-security-setting">
+      <h2 className="border-bottom mb-5">{t('security_settings.security_settings')}</h2>
+
+      <form onSubmit={handleSubmit(onSubmit)}>
+        <div className="vstack gap-3">
+          <PageListDisplaySettings adminGeneralSecurityContainer={adminGeneralSecurityContainer} t={t} />
+          <PageAccessRightsSettings adminGeneralSecurityContainer={adminGeneralSecurityContainer} t={t} />
+          <PageDeleteRightsSettings adminGeneralSecurityContainer={adminGeneralSecurityContainer} t={t} />
+          <UserHomepageDeletionSettings adminGeneralSecurityContainer={adminGeneralSecurityContainer} t={t} />
+          <CommentManageRightsSettings adminGeneralSecurityContainer={adminGeneralSecurityContainer} t={t} />
+          <SessionMaxAgeSettings register={register} t={t} />
+
+          <div className="text-center text-md-start offset-md-3 col-md-5">
+            <button
+              type="submit"
+              className="btn btn-primary"
+              disabled={adminGeneralSecurityContainer.state.retrieveError != null}
+            >
+              {t('Update')}
+            </button>
+          </div>
+        </div>
+      </form>
+    </div>
+  );
+};
+
+export const SecuritySetting = withUnstatedContainers(SecuritySettingComponent, [AdminGeneralSecurityContainer]);

+ 65 - 0
apps/app/src/client/components/Admin/Security/SecuritySetting/types.ts

@@ -0,0 +1,65 @@
+import { PageDeleteConfigValue, type IPageDeleteConfigValue } from '~/interfaces/page-delete-config';
+
+export const DeletionTypeForT = Object.freeze({
+  Deletion: 'deletion',
+  CompleteDeletion: 'complete_deletion',
+  RecursiveDeletion: 'recursive_deletion',
+  RecursiveCompleteDeletion: 'recursive_complete_deletion',
+} as const);
+
+export const DeletionType = Object.freeze({
+  Deletion: 'deletion',
+  CompleteDeletion: 'completeDeletion',
+  RecursiveDeletion: 'recursiveDeletion',
+  RecursiveCompleteDeletion: 'recursiveCompleteDeletion',
+} as const);
+
+export type DeletionTypeKey = keyof typeof DeletionType;
+export type DeletionTypeValue = typeof DeletionType[DeletionTypeKey];
+
+export const getDeletionTypeForT = (deletionType: DeletionTypeValue): string => {
+  switch (deletionType) {
+    case DeletionType.Deletion:
+      return DeletionTypeForT.Deletion;
+    case DeletionType.RecursiveDeletion:
+      return DeletionTypeForT.RecursiveDeletion;
+    case DeletionType.CompleteDeletion:
+      return DeletionTypeForT.CompleteDeletion;
+    case DeletionType.RecursiveCompleteDeletion:
+      return DeletionTypeForT.RecursiveCompleteDeletion;
+  }
+};
+
+export const getDeleteConfigValueForT = (deleteConfigValue: IPageDeleteConfigValue | null): string => {
+  switch (deleteConfigValue) {
+    case PageDeleteConfigValue.Anyone:
+    case null:
+      return 'security_settings.anyone';
+    case PageDeleteConfigValue.Inherit:
+      return 'security_settings.inherit';
+    case PageDeleteConfigValue.AdminOnly:
+      return 'security_settings.admin_only';
+    case PageDeleteConfigValue.AdminAndAuthor:
+      return 'security_settings.admin_and_author';
+    default:
+      return 'security_settings.anyone';
+  }
+};
+
+/**
+ * Return true if "deletionType" is DeletionType.RecursiveDeletion or DeletionType.RecursiveCompleteDeletion.
+ * @param deletionType Deletion type
+ * @returns boolean
+ */
+export const isRecursiveDeletion = (deletionType: DeletionTypeValue): boolean => {
+  return deletionType === DeletionType.RecursiveDeletion || deletionType === DeletionType.RecursiveCompleteDeletion;
+};
+
+/**
+ * Return true if "deletionType" is DeletionType.Deletion or DeletionType.RecursiveDeletion.
+ * @param deletionType Deletion type
+ * @returns boolean
+ */
+export const isTypeDeletion = (deletionType: DeletionTypeValue): boolean => {
+  return deletionType === DeletionType.Deletion || deletionType === DeletionType.RecursiveDeletion;
+};

+ 3 - 2
apps/app/src/client/services/AdminLdapSecurityContainer.js

@@ -87,9 +87,10 @@ export default class AdminLdapSecurityContainer extends Container {
 
   /**
    * Change ldapBindMode
+   * @param {boolean} isUserBind true: User Bind, false: Admin Bind
    */
-  changeLdapBindMode() {
-    this.setState({ isUserBind: !this.state.isUserBind });
+  changeLdapBindMode(isUserBind) {
+    this.setState({ isUserBind });
   }
 
   /**

+ 3 - 3
apps/app/src/client/services/renderer/renderer.tsx

@@ -63,7 +63,7 @@ export const generateViewOptions = (
   remarkPlugins.push(
     math,
     [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri, isDarkMode: config.isDarkMode }],
-    drawio.remarkPlugin,
+    [drawio.remarkPlugin, { isDarkMode: config.isDarkMode }],
     mermaid.remarkPlugin,
     xsvToTable.remarkPlugin,
     attachment.remarkPlugin,
@@ -171,7 +171,7 @@ export const generateSimpleViewOptions = (
   remarkPlugins.push(
     math,
     [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri, isDarkMode: config.isDarkMode }],
-    drawio.remarkPlugin,
+    [drawio.remarkPlugin, { isDarkMode: config.isDarkMode }],
     mermaid.remarkPlugin,
     xsvToTable.remarkPlugin,
     attachment.remarkPlugin,
@@ -268,7 +268,7 @@ export const generatePreviewOptions = (config: RendererConfigExt, pagePath: stri
   remarkPlugins.push(
     math,
     [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri, isDarkMode: config.isDarkMode }],
-    drawio.remarkPlugin,
+    [drawio.remarkPlugin, { isDarkMode: config.isDarkMode }],
     mermaid.remarkPlugin,
     xsvToTable.remarkPlugin,
     attachment.remarkPlugin,

+ 9 - 0
apps/app/src/features/openai/client/components/AiAssistant/AiAssistantSidebar/AiAssistantSidebar.module.scss

@@ -17,6 +17,15 @@
   .btn-submit {
     font-size: 1.1em;
   }
+
+  .thread-title-sticky {
+    -webkit-backdrop-filter: blur(10px);
+    backdrop-filter: blur(10px);
+  }
+
+  .input-form-area {
+    box-shadow: 0 -10px 20px 10px rgba(var(--bs-body-bg-rgb), 1);
+  }
 }
 
 // == Colors

+ 38 - 34
apps/app/src/features/openai/client/components/AiAssistant/AiAssistantSidebar/AiAssistantSidebar.tsx

@@ -82,6 +82,7 @@ const AiAssistantSidebarSubstance: React.FC<AiAssistantSidebarSubstanceProps> =
     headerIcon: headerIconForKnowledgeAssistant,
     headerText: headerTextForKnowledgeAssistant,
     placeHolder: placeHolderForKnowledgeAssistant,
+    threadTitleView: threadTitleViewForKnowledgeAssistant,
   } = useKnowledgeAssistant();
 
   const {
@@ -432,47 +433,50 @@ const AiAssistantSidebarSubstance: React.FC<AiAssistantSidebarSubstanceProps> =
             className="h-100"
             autoHide
           >
-            <div className="p-4 d-flex flex-column gap-4 flex-grow-1">
-              {threadData != null
-                ? (
-                  <div className="vstack gap-4 pb-2">
-                    {messageLogs.map(message => (
-                      <>
+            {!isEditorAssistant && threadTitleViewForKnowledgeAssistant}
+            <div className="p-4">
+              <div className="d-flex flex-column gap-4 flex-grow-1">
+                { threadData != null
+                  ? (
+                    <div className="vstack gap-4 pb-2">
+                      { messageLogs.map(message => (
+                        <>
+                          <MessageCard
+                            role={message.isUserMessage ? 'user' : 'assistant'}
+                            additionalItem={messageCardAdditionalItemForGeneratedMessage(message.id)}
+                          >
+                            {message.content}
+                          </MessageCard>
+                        </>
+                      )) }
+                      { generatingAnswerMessage != null && (
                         <MessageCard
-                          role={message.isUserMessage ? 'user' : 'assistant'}
-                          additionalItem={messageCardAdditionalItemForGeneratedMessage(message.id)}
+                          role="assistant"
+                          additionalItem={messageCardAdditionalItemForGeneratingMessage}
                         >
-                          {message.content}
+                          {generatingAnswerMessage.content}
                         </MessageCard>
-                      </>
-                    ))}
-                    {generatingAnswerMessage != null && (
-                      <MessageCard
-                        role="assistant"
-                        additionalItem={messageCardAdditionalItemForGeneratingMessage}
-                      >
-                        {generatingAnswerMessage.content}
-                      </MessageCard>
-                    )}
-                    {isEditorAssistant && partialContentWarnLabel}
-                    {messageLogs.length > 0 && (
-                      <div className="d-flex justify-content-center">
-                        <span className="bg-body-tertiary text-body-secondary rounded-pill px-3 py-1" style={{ fontSize: 'smaller' }}>
-                          {t('sidebar_ai_assistant.caution_against_hallucination')}
-                        </span>
-                      </div>
-                    )}
-                  </div>
-                )
-                : (
-                  <>{initialView}</>
-                )
-              }
+                      )}
+                      { isEditorAssistant && partialContentWarnLabel }
+                      { messageLogs.length > 0 && (
+                        <div className="d-flex justify-content-center">
+                          <span className="bg-body-tertiary text-body-secondary rounded-pill px-3 py-1" style={{ fontSize: 'smaller' }}>
+                            {t('sidebar_ai_assistant.caution_against_hallucination')}
+                          </span>
+                        </div>
+                      )}
+                    </div>
+                  )
+                  : (
+                    <>{ initialView }</>
+                  )
+                }
+              </div>
             </div>
           </SimpleBar>
         </div>
 
-        <div className="position-sticky bottom-0 bg-body z-2 p-3 border-top">
+        <div className="input-form-area position-sticky bg-body z-2 p-3">
           <form onSubmit={form.handleSubmit(submit)} className="flex-fill vstack gap-1">
             <Controller
               name="input"

+ 32 - 4
apps/app/src/features/openai/client/services/knowledge-assistant.tsx

@@ -61,6 +61,7 @@ type UseKnowledgeAssistant = () => {
   processMessage: ProcessMessage
   form: UseFormReturn<FormData>
   resetForm: () => void
+  threadTitleView: JSX.Element
 
   // Views
   initialView: JSX.Element
@@ -72,8 +73,8 @@ type UseKnowledgeAssistant = () => {
 
 export const useKnowledgeAssistant: UseKnowledgeAssistant = () => {
   // Hooks
-  const aiAssistantSidebarData = useAiAssistantSidebarStatus();
-  const { aiAssistantData, threadData } = aiAssistantSidebarData ?? {};
+  const aiAssistantSidebarData, refreshThreadData = useAiAssistantSidebarStatus();
+  const { aiAssistantData } = aiAssistantSidebarData ?? {};
   const { mutate: mutateRecentThreads } = useSWRINFxRecentThreads();
   const { trigger: mutateThreadData } = useSWRMUTxThreads(aiAssistantData?._id);
   const { t } = useTranslation();
@@ -85,6 +86,9 @@ export const useKnowledgeAssistant: UseKnowledgeAssistant = () => {
       extendedThinkingMode: false,
     },
   });
+  const handleBackToInitialView = useCallback(() => {
+    refreshThreadData(undefined);
+  }, [refreshThreadData]);
 
   // Functions
   const resetForm = useCallback(() => {
@@ -141,8 +145,8 @@ export const useKnowledgeAssistant: UseKnowledgeAssistant = () => {
   }, []);
 
   const headerText = useMemo(() => {
-    return <>{threadData?.title ?? aiAssistantData?.name}</>;
-  }, [aiAssistantData?.name, threadData?.title]);
+    return <>{aiAssistantData?.name}</>;
+  }, [aiAssistantData?.name]);
 
   const placeHolder = useMemo(() => { return 'sidebar_ai_assistant.knowledge_assistant_placeholder' }, []);
 
@@ -231,12 +235,36 @@ export const useKnowledgeAssistant: UseKnowledgeAssistant = () => {
     );
   }, [dropdownOpen, toggleDropdown, form, t]);
 
+  const threadTitleView = useMemo(() => {
+    const { threadData } = aiAssistantSidebarData ?? {};
+
+    if (threadData?.title == null) {
+      return <></>;
+    }
+
+    return (
+      <div className="thread-title-sticky sticky-top bg-body bg-opacity-75 py-2 px-3 z-1 ">
+        <div className="d-flex align-items-center gap-2">
+          <button
+            type="button"
+            className="btn btn-sm btn-link p-0 text-secondary"
+            onClick={handleBackToInitialView}
+          >
+            <span className="material-symbols-outlined">chevron_left</span>
+          </button>
+          <span className="text-truncate small">{threadData.title}</span>
+        </div>
+      </div>
+    );
+  }, [aiAssistantSidebarData, handleBackToInitialView]);
+
   return {
     createThread,
     postMessage,
     processMessage,
     form,
     resetForm,
+    threadTitleView,
 
     // Views
     initialView,

+ 3 - 3
apps/app/src/services/general-xss-filter/general-xss-filter.spec.ts

@@ -1,7 +1,6 @@
 import { generalXssFilter } from './general-xss-filter';
 
 describe('generalXssFilter', () => {
-
   test('should be sanitize script tag', () => {
     // Act
     const result = generalXssFilter.process('<script>alert("XSS")</script>');
@@ -12,7 +11,9 @@ describe('generalXssFilter', () => {
 
   test('should be sanitize nested script tag recursively', () => {
     // Act
-    const result = generalXssFilter.process('<scr<script>ipt>alert("XSS")</scr<script>ipt>');
+    const result = generalXssFilter.process(
+      '<scr<script>ipt>alert("XSS")</scr<script>ipt>',
+    );
 
     // Assert
     expect(result).toBe('alert("XSS")');
@@ -35,5 +36,4 @@ describe('generalXssFilter', () => {
     // Assert
     expect(result).toBe('<span>text</span>');
   });
-
 });

+ 4 - 5
apps/app/src/services/general-xss-filter/general-xss-filter.ts

@@ -7,11 +7,12 @@ const option: IFilterXSSOptions = {
   stripIgnoreTag: true,
   stripIgnoreTagBody: false, // see https://github.com/growilabs/growi/pull/505
   css: false,
-  escapeHtml: (html) => { return html }, // resolve https://github.com/growilabs/growi/issues/221
+  escapeHtml: (html) => {
+    return html;
+  }, // resolve https://github.com/growilabs/growi/issues/221
 };
 
 class GeneralXssFilter extends FilterXSS {
-
   override process(document: string | undefined): string {
     let count = 0;
     let currDoc = document;
@@ -26,12 +27,10 @@ class GeneralXssFilter extends FilterXSS {
 
       prevDoc = currDoc;
       currDoc = super.process(currDoc ?? '');
-    }
-    while (currDoc !== prevDoc);
+    } while (currDoc !== prevDoc);
 
     return currDoc;
   }
-
 }
 
 export const generalXssFilter = new GeneralXssFilter(option);

+ 6 - 2
apps/app/src/services/layout/use-should-expand-content.ts

@@ -3,14 +3,18 @@ import { useAtomValue } from 'jotai';
 
 import { isContainerFluidAtom } from '~/states/server-configurations';
 
-const useDetermineExpandContent = (expandContentWidth?: boolean | null): boolean => {
+const useDetermineExpandContent = (
+  expandContentWidth?: boolean | null,
+): boolean => {
   const dataIsContainerFluid = useAtomValue(isContainerFluidAtom);
 
   const isContainerFluidDefault = dataIsContainerFluid;
   return expandContentWidth ?? isContainerFluidDefault ?? false;
 };
 
-export const useShouldExpandContent = (data?: IPage | IPagePopulatedToShowRevision | boolean | null): boolean => {
+export const useShouldExpandContent = (
+  data?: IPage | IPagePopulatedToShowRevision | boolean | null,
+): boolean => {
   const expandContentWidth = (() => {
     // when data is null
     if (data == null) {

+ 6 - 5
apps/app/src/services/renderer/markdown-it/PreProcessor/EasyGrid.js

@@ -1,10 +1,11 @@
 export default class EasyGrid {
-
   process(markdown) {
     // see: https://regex101.com/r/7NWvUU/2
-    return markdown.replace(/:::\s*editable-row[\r\n]((.|[\r\n])*?)[\r\n]:::/gm, (all, group) => {
-      return group;
-    });
+    return markdown.replace(
+      /:::\s*editable-row[\r\n]((.|[\r\n])*?)[\r\n]:::/gm,
+      (all, group) => {
+        return group;
+      },
+    );
   }
-
 }

+ 13 - 6
apps/app/src/services/renderer/recommended-whitelist.spec.ts

@@ -1,9 +1,8 @@
 import { notDeepEqual } from 'assert';
 
-import { tagNames, attributes } from './recommended-whitelist';
+import { attributes, tagNames } from './recommended-whitelist';
 
 describe('recommended-whitelist', () => {
-
   test('.tagNames should return iframe tag', () => {
     expect(tagNames).not.toBeNull();
     expect(tagNames).includes('iframe');
@@ -52,7 +51,10 @@ describe('recommended-whitelist', () => {
     assert(attributes != null);
 
     expect(Object.keys(attributes)).includes('a');
-    expect(attributes.a).not.toContainEqual(['className', 'data-footnote-backref']);
+    expect(attributes.a).not.toContainEqual([
+      'className',
+      'data-footnote-backref',
+    ]);
   });
 
   test('.attributes.ul should allow class and className by excluding partial className specification', () => {
@@ -61,7 +63,10 @@ describe('recommended-whitelist', () => {
     assert(attributes != null);
 
     expect(Object.keys(attributes)).includes('a');
-    expect(attributes.a).not.toContainEqual(['className', 'data-footnote-backref']);
+    expect(attributes.a).not.toContainEqual([
+      'className',
+      'data-footnote-backref',
+    ]);
   });
 
   test('.attributes.li should allow class and className by excluding partial className specification', () => {
@@ -70,7 +75,9 @@ describe('recommended-whitelist', () => {
     assert(attributes != null);
 
     expect(Object.keys(attributes)).includes('a');
-    expect(attributes.a).not.toContainEqual(['className', 'data-footnote-backref']);
+    expect(attributes.a).not.toContainEqual([
+      'className',
+      'data-footnote-backref',
+    ]);
   });
-
 });

+ 31 - 20
apps/app/src/services/renderer/recommended-whitelist.ts

@@ -9,7 +9,9 @@ type ExtractPropertyDefinition<T> = T extends Record<string, (infer U)[]>
 
 type PropertyDefinition = ExtractPropertyDefinition<NonNullable<Attributes>>;
 
-const excludeRestrictedClassAttributes = (propertyDefinitions: PropertyDefinition[]): PropertyDefinition[] => {
+const excludeRestrictedClassAttributes = (
+  propertyDefinitions: PropertyDefinition[],
+): PropertyDefinition[] => {
   if (propertyDefinitions == null) {
     return propertyDefinitions;
   }
@@ -18,15 +20,24 @@ const excludeRestrictedClassAttributes = (propertyDefinitions: PropertyDefinitio
     if (!Array.isArray(propertyDefinition)) {
       return true;
     }
-    return propertyDefinition[0] !== 'class' && propertyDefinition[0] !== 'className';
+    return (
+      propertyDefinition[0] !== 'class' && propertyDefinition[0] !== 'className'
+    );
   });
 };
 
 // generate relaxed schema
-const relaxedSchemaAttributes: Record<string, PropertyDefinition[]> = structuredClone(defaultSchema.attributes) ?? {};
-relaxedSchemaAttributes.a = excludeRestrictedClassAttributes(relaxedSchemaAttributes.a);
-relaxedSchemaAttributes.ul = excludeRestrictedClassAttributes(relaxedSchemaAttributes.ul);
-relaxedSchemaAttributes.li = excludeRestrictedClassAttributes(relaxedSchemaAttributes.li);
+const relaxedSchemaAttributes: Record<string, PropertyDefinition[]> =
+  structuredClone(defaultSchema.attributes) ?? {};
+relaxedSchemaAttributes.a = excludeRestrictedClassAttributes(
+  relaxedSchemaAttributes.a,
+);
+relaxedSchemaAttributes.ul = excludeRestrictedClassAttributes(
+  relaxedSchemaAttributes.ul,
+);
+relaxedSchemaAttributes.li = excludeRestrictedClassAttributes(
+  relaxedSchemaAttributes.li,
+);
 
 /**
  * reference: https://meta.stackexchange.com/questions/1777/what-html-tags-are-allowed-on-stack-exchange-sites,
@@ -34,23 +45,23 @@ relaxedSchemaAttributes.li = excludeRestrictedClassAttributes(relaxedSchemaAttri
  */
 
 export const tagNames: Array<string> = [
-  ...defaultSchema.tagNames ?? [],
-  '-', 'bdi',
+  ...(defaultSchema.tagNames ?? []),
+  '-',
+  'bdi',
   'button',
-  'col', 'colgroup',
+  'col',
+  'colgroup',
   'data',
   'iframe',
   'video',
-  'rb', 'u',
+  'rb',
+  'u',
 ];
 
-export const attributes: Attributes = deepmerge(
-  relaxedSchemaAttributes,
-  {
-    iframe: ['allow', 'referrerpolicy', 'sandbox', 'src'],
-    video: ['controls', 'src', 'muted', 'preload', 'width', 'height', 'autoplay'],
-    // The special value 'data*' as a property name can be used to allow all data properties.
-    // see: https://github.com/syntax-tree/hast-util-sanitize/
-    '*': ['key', 'class', 'className', 'style', 'role', 'data*'],
-  },
-);
+export const attributes: Attributes = deepmerge(relaxedSchemaAttributes, {
+  iframe: ['allow', 'referrerpolicy', 'sandbox', 'src'],
+  video: ['controls', 'src', 'muted', 'preload', 'width', 'height', 'autoplay'],
+  // The special value 'data*' as a property name can be used to allow all data properties.
+  // see: https://github.com/syntax-tree/hast-util-sanitize/
+  '*': ['key', 'class', 'className', 'style', 'role', 'data*'],
+});

+ 6 - 3
apps/app/src/services/renderer/rehype-plugins/add-class.ts

@@ -1,6 +1,6 @@
 // See: https://github.com/martypdx/rehype-add-classes for the original implementation.
 // Re-implemeted in TypeScript.
-import type { Nodes as HastNode, Element, Properties } from 'hast';
+import type { Element, Nodes as HastNode, Properties } from 'hast';
 import { selectAll } from 'hast-util-select';
 import type { Plugin } from 'unified';
 
@@ -9,7 +9,10 @@ export type ClassName = string; // e.g. 'header'
 export type Additions = Record<SelectorName, ClassName>;
 export type AdditionsEntry = [SelectorName, ClassName];
 
-export const addClassToProperties = (properties: Properties | undefined, className: string): void => {
+export const addClassToProperties = (
+  properties: Properties | undefined,
+  className: string,
+): void => {
   if (properties == null) {
     return;
   }
@@ -42,5 +45,5 @@ const adder = (entry: AdditionsEntry) => {
 export const rehypePlugin: Plugin<[Additions]> = (additions) => {
   const adders = Object.entries(additions).map(adder);
 
-  return node => adders.forEach(a => a(node as HastNode));
+  return (node) => adders.forEach((a) => a(node as HastNode));
 };

+ 4 - 1
apps/app/src/services/renderer/rehype-plugins/add-inline-code-property.ts

@@ -3,7 +3,10 @@ import type { Plugin } from 'unified';
 import { is } from 'unist-util-is';
 import { visitParents } from 'unist-util-visit-parents';
 
-const isInlineCodeTag = (node: Element, parent: Element | Root | null): boolean => {
+const isInlineCodeTag = (
+  node: Element,
+  parent: Element | Root | null,
+): boolean => {
   if (node.tagName !== 'code') {
     return false;
   }

+ 4 - 2
apps/app/src/services/renderer/rehype-plugins/add-line-number-attribute.ts

@@ -1,11 +1,13 @@
 import type { Element } from 'hast';
 import type { Schema as SanitizeOption } from 'hast-util-sanitize';
 import type { Plugin } from 'unified';
-import { visit, EXIT, CONTINUE } from 'unist-util-visit';
+import { CONTINUE, EXIT, visit } from 'unist-util-visit';
 
 import { addClassToProperties } from './add-class';
 
-const REGEXP_TARGET_TAGNAMES = new RegExp(/^(h1|h2|h3|h4|h5|h6|p|img|pre|blockquote|hr|ol|ul|table)$/);
+const REGEXP_TARGET_TAGNAMES = new RegExp(
+  /^(h1|h2|h3|h4|h5|h6|p|img|pre|blockquote|hr|ol|ul|table)$/,
+);
 
 export const rehypePlugin: Plugin = () => {
   return (tree) => {

+ 21 - 11
apps/app/src/services/renderer/rehype-plugins/keyword-highlighter.ts

@@ -1,8 +1,7 @@
-import type { Root, Element, Text } from 'hast';
+import type { Element, Root, Text } from 'hast';
 import rehypeRewrite from 'rehype-rewrite';
 import type { Plugin } from 'unified';
 
-
 /**
  * This method returns ['foo', 'bar', 'foo']
  *  when the arguments are { keyword: 'foo', value: 'foobarfoo' }
@@ -50,7 +49,12 @@ function wrapWithEm(textElement: Text): Element {
   };
 }
 
-function highlight(lowercasedKeyword: string, node: Text, index: number, parent: Root | Element): void {
+function highlight(
+  lowercasedKeyword: string,
+  node: Text,
+  index: number,
+  parent: Root | Element,
+): void {
   if (node.value.toLowerCase().includes(lowercasedKeyword)) {
     const splitted = splitWithKeyword(lowercasedKeyword, node.value);
 
@@ -67,25 +71,31 @@ function highlight(lowercasedKeyword: string, node: Text, index: number, parent:
   }
 }
 
-
 export type KeywordHighlighterPluginParams = {
-  keywords?: string | string[],
-}
+  keywords?: string | string[];
+};
 
-export const rehypePlugin: Plugin<[KeywordHighlighterPluginParams]> = (options) => {
+export const rehypePlugin: Plugin<[KeywordHighlighterPluginParams]> = (
+  options,
+) => {
   if (options?.keywords == null) {
-    return node => node;
+    return (node) => node;
   }
 
-  const keywords = (typeof options.keywords === 'string') ? [options.keywords] : options.keywords;
+  const keywords =
+    typeof options.keywords === 'string'
+      ? [options.keywords]
+      : options.keywords;
 
-  const lowercasedKeywords = keywords.map(keyword => keyword.toLowerCase());
+  const lowercasedKeywords = keywords.map((keyword) => keyword.toLowerCase());
 
   // return rehype-rewrite with hithlighter
   return rehypeRewrite.bind(this)({
     rewrite: (node, index, parent) => {
       if (parent != null && index != null && node.type === 'text') {
-        lowercasedKeywords.forEach(keyword => highlight(keyword, node, index, parent));
+        lowercasedKeywords.forEach((keyword) =>
+          highlight(keyword, node, index, parent),
+        );
       }
     },
   });

+ 45 - 39
apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.spec.ts

@@ -9,45 +9,51 @@ import { pukiwikiLikeLinker } from '../remark-plugins/pukiwiki-like-linker';
 import { relativeLinksByPukiwikiLikeLinker } from './relative-links-by-pukiwiki-like-linker';
 
 describe('relativeLinksByPukiwikiLikeLinker', () => {
-
   /* eslint-disable indent */
   describe.each`
-    input                                   | expectedHref                        | expectedValue
-    ${'[[/page]]'}                          | ${'/page'}                          | ${'/page'}
-    ${'[[./page]]'}                         | ${'/user/admin/page'}               | ${'./page'}
-    ${'[[Title>./page]]'}                   | ${'/user/admin/page'}               | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}            | ${'Title'}
-    ${'[[/page?q=foo#header]]'}             | ${'/page?q=foo#header'}             | ${'/page?q=foo#header'}
-    ${'[[./page?q=foo#header]]'}            | ${'/user/admin/page?q=foo#header'}  | ${'./page?q=foo#header'}
-    ${'[[Title>./page?q=foo#header]]'}      | ${'/user/admin/page?q=foo#header'}  | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}            | ${'Title'}
-  `('should convert relative links correctly', ({ input, expectedHref, expectedValue }) => {
-  /* eslint-enable indent */
-
-    test(`when the input is '${input}'`, () => {
-      // setup:
-      const processor = unified()
-        .use(parse)
-        .use(pukiwikiLikeLinker)
-        .use(rehype)
-        .use(relativeLinksByPukiwikiLikeLinker, { pagePath: '/user/admin' });
-
-      // when:
-      const mdast = processor.parse(input);
-      const hast = processor.runSync(mdast) as HastNode;
-      const anchorElement = select('a', hast);
-
-      // then
-      expect(anchorElement).not.toBeNull();
-      expect(anchorElement?.properties).not.toBeNull();
-      expect((anchorElement?.properties?.className as string).startsWith('pukiwiki-like-linker')).toBeTruthy();
-      expect(anchorElement?.properties?.href).toEqual(expectedHref);
-
-      expect(anchorElement?.children[0]).not.toBeNull();
-      expect(anchorElement?.children[0].type).toEqual('text');
-      expect((anchorElement?.children[0] as HastNode as Text).value).toEqual(expectedValue);
-
-    });
-  });
-
+    input                              | expectedHref                       | expectedValue
+    ${'[[/page]]'}                     | ${'/page'}                         | ${'/page'}
+    ${'[[./page]]'}                    | ${'/user/admin/page'}              | ${'./page'}
+    ${'[[Title>./page]]'}              | ${'/user/admin/page'}              | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'}           | ${'Title'}
+    ${'[[/page?q=foo#header]]'}        | ${'/page?q=foo#header'}            | ${'/page?q=foo#header'}
+    ${'[[./page?q=foo#header]]'}       | ${'/user/admin/page?q=foo#header'} | ${'./page?q=foo#header'}
+    ${'[[Title>./page?q=foo#header]]'} | ${'/user/admin/page?q=foo#header'} | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'}           | ${'Title'}
+  `(
+    'should convert relative links correctly',
+    ({ input, expectedHref, expectedValue }) => {
+      /* eslint-enable indent */
+
+      test(`when the input is '${input}'`, () => {
+        // setup:
+        const processor = unified()
+          .use(parse)
+          .use(pukiwikiLikeLinker)
+          .use(rehype)
+          .use(relativeLinksByPukiwikiLikeLinker, { pagePath: '/user/admin' });
+
+        // when:
+        const mdast = processor.parse(input);
+        const hast = processor.runSync(mdast) as HastNode;
+        const anchorElement = select('a', hast);
+
+        // then
+        expect(anchorElement).not.toBeNull();
+        expect(anchorElement?.properties).not.toBeNull();
+        expect(
+          (anchorElement?.properties?.className as string).startsWith(
+            'pukiwiki-like-linker',
+          ),
+        ).toBeTruthy();
+        expect(anchorElement?.properties?.href).toEqual(expectedHref);
+
+        expect(anchorElement?.children[0]).not.toBeNull();
+        expect(anchorElement?.children[0].type).toEqual('text');
+        expect((anchorElement?.children[0] as HastNode as Text).value).toEqual(
+          expectedValue,
+        );
+      });
+    },
+  );
 });

+ 6 - 2
apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.ts

@@ -3,8 +3,10 @@ import { selectAll } from 'hast-util-select';
 import type { Plugin } from 'unified';
 
 import {
+  type IAnchorsSelector,
+  type IUrlResolver,
+  type RelativeLinksPluginParams,
   relativeLinks,
-  type IAnchorsSelector, type IUrlResolver, type RelativeLinksPluginParams,
 } from './relative-links';
 
 const customAnchorsSelector: IAnchorsSelector = (node) => {
@@ -17,7 +19,9 @@ const customUrlResolver: IUrlResolver = (relativeHref, basePath) => {
   return new URL(relativeHref, baseUrl);
 };
 
-export const relativeLinksByPukiwikiLikeLinker: Plugin<[RelativeLinksPluginParams]> = (options = {}) => {
+export const relativeLinksByPukiwikiLikeLinker: Plugin<
+  [RelativeLinksPluginParams]
+> = (options = {}) => {
   return relativeLinks.bind(this)({
     ...options,
     anchorsSelector: customAnchorsSelector,

+ 31 - 33
apps/app/src/services/renderer/rehype-plugins/relative-links.spec.ts

@@ -1,4 +1,3 @@
-
 import type { Nodes as HastNode } from 'hast';
 import { select } from 'hast-util-select';
 import parse from 'remark-parse';
@@ -8,7 +7,6 @@ import { unified } from 'unified';
 import { relativeLinks } from './relative-links';
 
 describe('relativeLinks', () => {
-
   test('do nothing when the options does not have pagePath', () => {
     // setup
     const processor = unified()
@@ -27,10 +25,9 @@ describe('relativeLinks', () => {
 
   test.concurrent.each`
     originalHref
-      ${'http://example.com/Sandbox'}
-      ${'#header'}
-    `('leaves the original href \'$originalHref\' as-is', ({ originalHref }) => {
-
+    ${'http://example.com/Sandbox'}
+    ${'#header'}
+  `("leaves the original href '$originalHref' as-is", ({ originalHref }) => {
     // setup
     const pagePath = '/foo/bar/baz';
     const processor = unified()
@@ -48,33 +45,34 @@ describe('relativeLinks', () => {
   });
 
   test.concurrent.each`
-    originalHref                        | expectedHref
-      ${'/Sandbox'}                     | ${'/Sandbox'}
-      ${'/Sandbox?q=foo'}               | ${'/Sandbox?q=foo'}
-      ${'/Sandbox#header'}              | ${'/Sandbox#header'}
-      ${'/Sandbox?q=foo#header'}        | ${'/Sandbox?q=foo#header'}
-      ${'./Sandbox'}                    | ${'/foo/bar/Sandbox'}
-      ${'./Sandbox?q=foo'}              | ${'/foo/bar/Sandbox?q=foo'}
-      ${'./Sandbox#header'}             | ${'/foo/bar/Sandbox#header'}
-      ${'./Sandbox?q=foo#header'}       | ${'/foo/bar/Sandbox?q=foo#header'}
-    `('rewrites the original href \'$originalHref\' to \'$expectedHref\'', ({ originalHref, expectedHref }) => {
+    originalHref                | expectedHref
+    ${'/Sandbox'}               | ${'/Sandbox'}
+    ${'/Sandbox?q=foo'}         | ${'/Sandbox?q=foo'}
+    ${'/Sandbox#header'}        | ${'/Sandbox#header'}
+    ${'/Sandbox?q=foo#header'}  | ${'/Sandbox?q=foo#header'}
+    ${'./Sandbox'}              | ${'/foo/bar/Sandbox'}
+    ${'./Sandbox?q=foo'}        | ${'/foo/bar/Sandbox?q=foo'}
+    ${'./Sandbox#header'}       | ${'/foo/bar/Sandbox#header'}
+    ${'./Sandbox?q=foo#header'} | ${'/foo/bar/Sandbox?q=foo#header'}
+  `(
+    "rewrites the original href '$originalHref' to '$expectedHref'",
+    ({ originalHref, expectedHref }) => {
+      // setup
+      const pagePath = '/foo/bar/baz';
+      const processor = unified()
+        .use(parse)
+        .use(remarkRehype)
+        .use(relativeLinks, { pagePath });
 
-    // setup
-    const pagePath = '/foo/bar/baz';
-    const processor = unified()
-      .use(parse)
-      .use(remarkRehype)
-      .use(relativeLinks, { pagePath });
-
-    // when
-    const mdastTree = processor.parse(`[link](${originalHref})`);
-    const hastTree = processor.runSync(mdastTree) as HastNode;
-
-    // then
-    const anchorElement = select('a', hastTree);
-    expect(anchorElement).not.toBeNull();
-    expect(anchorElement?.properties).not.toBeNull();
-    expect(anchorElement?.properties?.href).toBe(expectedHref);
-  });
+      // when
+      const mdastTree = processor.parse(`[link](${originalHref})`);
+      const hastTree = processor.runSync(mdastTree) as HastNode;
 
+      // then
+      const anchorElement = select('a', hastTree);
+      expect(anchorElement).not.toBeNull();
+      expect(anchorElement?.properties).not.toBeNull();
+      expect(anchorElement?.properties?.href).toBe(expectedHref);
+    },
+  );
 });

+ 14 - 8
apps/app/src/services/renderer/rehype-plugins/relative-links.ts

@@ -1,11 +1,10 @@
 import assert from 'assert';
 
-import type { Nodes as HastNode, Element } from 'hast';
+import type { Element, Nodes as HastNode } from 'hast';
 import { selectAll } from 'hast-util-select';
 import isAbsolute from 'is-absolute-url';
 import type { Plugin } from 'unified';
 
-
 export type IAnchorsSelector = (node: HastNode) => Element[];
 export type IUrlResolver = (relativeHref: string, basePath: string) => URL;
 
@@ -29,12 +28,14 @@ const isAnchorLink = (href: string): boolean => {
 };
 
 export type RelativeLinksPluginParams = {
-  pagePath?: string,
-  anchorsSelector?: IAnchorsSelector,
-  urlResolver?: IUrlResolver,
-}
+  pagePath?: string;
+  anchorsSelector?: IAnchorsSelector;
+  urlResolver?: IUrlResolver;
+};
 
-export const relativeLinks: Plugin<[RelativeLinksPluginParams]> = (options = {}) => {
+export const relativeLinks: Plugin<[RelativeLinksPluginParams]> = (
+  options = {},
+) => {
   const anchorsSelector = options.anchorsSelector ?? defaultAnchorsSelector;
   const urlResolver = options.urlResolver ?? defaultUrlResolver;
 
@@ -50,7 +51,12 @@ export const relativeLinks: Plugin<[RelativeLinksPluginParams]> = (options = {})
       assert(anchor.properties != null);
 
       const href = anchor.properties.href;
-      if (href == null || typeof href !== 'string' || isAbsolute(href) || isAnchorLink(href)) {
+      if (
+        href == null ||
+        typeof href !== 'string' ||
+        isAbsolute(href) ||
+        isAnchorLink(href)
+      ) {
         return;
       }
 

+ 8 - 7
apps/app/src/services/renderer/rehype-plugins/relocate-toc.ts

@@ -1,11 +1,11 @@
-import rehypeToc from 'rehype-toc';
 import type { HtmlElementNode } from 'rehype-toc';
+import rehypeToc from 'rehype-toc';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
 type StoreTocPluginParams = {
-  storeTocNode: (toc: HtmlElementNode) => void,
-}
+  storeTocNode: (toc: HtmlElementNode) => void;
+};
 
 export const rehypePluginStore: Plugin<[StoreTocPluginParams]> = (options) => {
   return rehypeToc.bind(this)({
@@ -21,7 +21,6 @@ export const rehypePluginStore: Plugin<[StoreTocPluginParams]> = (options) => {
   });
 };
 
-
 // method for replace <ol> to <ul>
 const replaceOlToUl = (tree: HtmlElementNode) => {
   visit(tree, 'element', (node: HtmlElementNode) => {
@@ -32,10 +31,12 @@ const replaceOlToUl = (tree: HtmlElementNode) => {
 };
 
 type RestoreTocPluginParams = {
-  tocNode?: HtmlElementNode,
-}
+  tocNode?: HtmlElementNode;
+};
 
-export const rehypePluginRestore: Plugin<[RestoreTocPluginParams]> = (options) => {
+export const rehypePluginRestore: Plugin<[RestoreTocPluginParams]> = (
+  options,
+) => {
   const { tocNode } = options;
 
   return rehypeToc.bind(this)({

+ 10 - 6
apps/app/src/services/renderer/remark-plugins/attachment.ts

@@ -1,7 +1,6 @@
-import path from 'path';
-
 import type { Schema as SanitizeOption } from 'hast-util-sanitize';
 import type { Link } from 'mdast';
+import path from 'path';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
@@ -15,9 +14,15 @@ const isAttachmentLink = (url: string): boolean => {
 
 const rewriteNode = (node: Link) => {
   const attachmentId = path.basename(node.url);
-  const attachmentName = node.children[0] != null && node.children[0].type === 'text' ? node.children[0].value : '';
-
-  const data = node.data ?? (node.data = {});
+  const attachmentName =
+    node.children[0] != null && node.children[0].type === 'text'
+      ? node.children[0].value
+      : '';
+
+  if (node.data == null) {
+    node.data = {};
+  }
+  const data = node.data;
   data.hName = 'attachment';
   data.hProperties = {
     attachmentId,
@@ -26,7 +31,6 @@ const rewriteNode = (node: Link) => {
   };
 };
 
-
 export const remarkPlugin: Plugin = () => {
   return (tree) => {
     visit(tree, 'link', (node: Link) => {

+ 4 - 2
apps/app/src/services/renderer/remark-plugins/codeblock.ts

@@ -3,13 +3,15 @@ import type { InlineCode } from 'mdast';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
-
 const SUPPORTED_CODE = ['inline'];
 
 export const remarkPlugin: Plugin = () => {
   return (tree) => {
     visit(tree, 'inlineCode', (node: InlineCode) => {
-      const data = node.data || (node.data = {});
+      if (node.data == null) {
+        node.data = {};
+      }
+      const data = node.data;
       data.hProperties = { inline: 'true' }; // set 'true' explicitly because the empty string is evaluated as false for `if (inline) { ... }`
     });
   };

+ 11 - 6
apps/app/src/services/renderer/remark-plugins/echo-directive.ts

@@ -5,23 +5,26 @@ import type { LeafDirective, TextDirective } from 'mdast-util-directive';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
-
 function echoDirective(node: TextDirective | LeafDirective): ElementContent[] {
   const mark = node.type === 'textDirective' ? ':' : '::';
 
   return [
     h('span', `${mark}${node.name}`),
-    ...(node.children ?? []).map((child: Text) => h('span', `[${child.value}]`)),
+    ...(node.children ?? []).map((child: Text) =>
+      h('span', `[${child.value}]`),
+    ),
   ];
 }
 
 export const remarkPlugin: Plugin = () => {
   return (tree) => {
-
     visit(tree, 'textDirective', (node: TextDirective) => {
       const tagName = 'span';
 
-      const data = node.data ?? (node.data = {});
+      if (node.data == null) {
+        node.data = {};
+      }
+      const data = node.data;
       data.hName = tagName;
       data.hProperties = h(tagName, node.attributes ?? {}).properties;
       data.hChildren = echoDirective(node);
@@ -30,11 +33,13 @@ export const remarkPlugin: Plugin = () => {
     visit(tree, 'leafDirective', (node: LeafDirective) => {
       const tagName = 'div';
 
-      const data = node.data ?? (node.data = {});
+      if (node.data == null) {
+        node.data = {};
+      }
+      const data = node.data;
       data.hName = tagName;
       data.hProperties = h(tagName, node.attributes ?? {}).properties;
       data.hChildren = echoDirective(node);
     });
-
   };
 };

+ 2 - 3
apps/app/src/services/renderer/remark-plugins/emoji.ts

@@ -4,13 +4,12 @@ import { findAndReplace } from 'mdast-util-find-and-replace';
 import type { Plugin } from 'unified';
 
 export const remarkPlugin: Plugin = () => {
-  return function(tree: Root) {
+  return (tree: Root) => {
     findAndReplace(tree, [
-
       // Ref: https://github.com/remarkjs/remark-gemoji/blob/fb4d8a5021f02384e180c17f72f40d8dc698bd46/lib/index.js
       /:(\+1|[-\w]+):/g,
 
-      function(_, $1: string) {
+      (_, $1: string) => {
         const emoji = emojiData.emojis[$1]?.skins[0].native;
         return emoji ?? false;
       },

+ 13 - 16
apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.spec.ts

@@ -5,24 +5,20 @@ import { visit } from 'unist-util-visit';
 import { pukiwikiLikeLinker } from './pukiwiki-like-linker';
 
 describe('pukiwikiLikeLinker', () => {
-
   describe.each`
-    input                                   | expectedHref                    | expectedValue
-    ${'[[/page]]'}                          | ${'/page'}                      | ${'/page'}
-    ${'[[./page]]'}                         | ${'./page'}                     | ${'./page'}
-    ${'[[Title>./page]]'}                   | ${'./page'}                     | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}        | ${'Title'}
-    ${'[[/page?q=foo#header]]'}             | ${'/page?q=foo#header'}         | ${'/page?q=foo#header'}
-    ${'[[./page?q=foo#header]]'}            | ${'./page?q=foo#header'}        | ${'./page?q=foo#header'}
-    ${'[[Title>./page?q=foo#header]]'}      | ${'./page?q=foo#header'}        | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}        | ${'Title'}
+    input                              | expectedHref             | expectedValue
+    ${'[[/page]]'}                     | ${'/page'}               | ${'/page'}
+    ${'[[./page]]'}                    | ${'./page'}              | ${'./page'}
+    ${'[[Title>./page]]'}              | ${'./page'}              | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'} | ${'Title'}
+    ${'[[/page?q=foo#header]]'}        | ${'/page?q=foo#header'}  | ${'/page?q=foo#header'}
+    ${'[[./page?q=foo#header]]'}       | ${'./page?q=foo#header'} | ${'./page?q=foo#header'}
+    ${'[[Title>./page?q=foo#header]]'} | ${'./page?q=foo#header'} | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'} | ${'Title'}
   `('should parse correctly', ({ input, expectedHref, expectedValue }) => {
-
     test(`when the input is '${input}'`, () => {
       // setup:
-      const processor = unified()
-        .use(parse)
-        .use(pukiwikiLikeLinker);
+      const processor = unified().use(parse).use(pukiwikiLikeLinker);
 
       // when:
       const ast = processor.parse(input);
@@ -33,11 +29,12 @@ describe('pukiwikiLikeLinker', () => {
         expect(node.data.alias).toEqual(expectedValue);
         expect(node.data.permalink).toEqual(expectedHref);
         expect(node.data.hName).toEqual('a');
-        expect(node.data.hProperties.className.startsWith('pukiwiki-like-linker')).toBeTruthy();
+        expect(
+          node.data.hProperties.className.startsWith('pukiwiki-like-linker'),
+        ).toBeTruthy();
         expect(node.data.hProperties.href).toEqual(expectedHref);
         expect(node.data.hChildren[0].value).toEqual(expectedValue);
       });
     });
   });
-
 });

+ 34 - 26
apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.ts

@@ -2,27 +2,28 @@ import { fromMarkdown, toMarkdown } from 'mdast-util-wiki-link';
 import { syntax } from 'micromark-extension-wiki-link';
 import type { Plugin } from 'unified';
 
-
 type FromMarkdownExtension = {
   enter: {
-    wikiLink: (token: string) => void,
-  },
+    wikiLink: (token: string) => void;
+  };
   exit: {
-    wikiLinkTarget: (token: string) => void,
-    wikiLinkAlias: (token: string) => void,
-    wikiLink: (token: string) => void,
-  }
-}
+    wikiLinkTarget: (token: string) => void;
+    wikiLinkAlias: (token: string) => void;
+    wikiLink: (token: string) => void;
+  };
+};
 
 type FromMarkdownData = {
-  value: string | null,
+  value: string | null;
   data: {
-    alias: string | null,
-    hProperties: Record<string, unknown>,
-  }
-}
+    alias: string | null;
+    hProperties: Record<string, unknown>;
+  };
+};
 
-function swapTargetAndAlias(fromMarkdownExtension: FromMarkdownExtension): FromMarkdownExtension {
+function swapTargetAndAlias(
+  fromMarkdownExtension: FromMarkdownExtension,
+): FromMarkdownExtension {
   return {
     enter: fromMarkdownExtension.enter,
     exit: {
@@ -52,7 +53,7 @@ function swapTargetAndAlias(fromMarkdownExtension: FromMarkdownExtension): FromM
 /**
  * Implemented with reference to https://github.com/landakram/remark-wiki-link/blob/master/src/index.js
  */
-export const pukiwikiLikeLinker: Plugin = function() {
+export const pukiwikiLikeLinker: Plugin = function () {
   const data = this.data();
 
   function add(field: string, value) {
@@ -61,20 +62,27 @@ export const pukiwikiLikeLinker: Plugin = function() {
       if (Array.isArray(array)) {
         array.push(value);
       }
-    }
-    else {
+    } else {
       data[field] = [value];
     }
   }
 
-  add('micromarkExtensions', syntax({
-    aliasDivider: '>',
-  }));
-  add('fromMarkdownExtensions', swapTargetAndAlias(fromMarkdown({
-    wikiLinkClassName: 'pukiwiki-like-linker',
-    newClassName: ' ',
-    pageResolver: value => [value],
-    hrefTemplate: permalink => permalink,
-  })));
+  add(
+    'micromarkExtensions',
+    syntax({
+      aliasDivider: '>',
+    }),
+  );
+  add(
+    'fromMarkdownExtensions',
+    swapTargetAndAlias(
+      fromMarkdown({
+        wikiLinkClassName: 'pukiwiki-like-linker',
+        newClassName: ' ',
+        pageResolver: (value) => [value],
+        hrefTemplate: (permalink) => permalink,
+      }),
+    ),
+  );
   add('toMarkdownExtensions', toMarkdown({}));
 };

+ 6 - 8
apps/app/src/services/renderer/remark-plugins/xsv-to-table.ts

@@ -33,12 +33,10 @@ function rewriteNode(node: Node, lang: Lang) {
   }
 }
 
-export const remarkPlugin: Plugin = function() {
-  return (tree) => {
-    visit(tree, 'code', (node: Code) => {
-      if (isXsv(node.lang)) {
-        rewriteNode(node, node.lang);
-      }
-    });
-  };
+export const remarkPlugin: Plugin = () => (tree) => {
+  visit(tree, 'code', (node: Code) => {
+    if (isXsv(node.lang)) {
+      rewriteNode(node, node.lang);
+    }
+  });
 };

+ 53 - 39
apps/app/src/services/renderer/renderer.tsx

@@ -19,7 +19,10 @@ import { RehypeSanitizeType } from '~/interfaces/services/rehype-sanitize';
 import type { RendererConfig } from '~/interfaces/services/renderer';
 import loggerFactory from '~/utils/logger';
 
-import { tagNames as recommendedTagNames, attributes as recommendedAttributes } from './recommended-whitelist';
+import {
+  attributes as recommendedAttributes,
+  tagNames as recommendedTagNames,
+} from './recommended-whitelist';
 import * as addClass from './rehype-plugins/add-class';
 import * as addInlineProperty from './rehype-plugins/add-inline-code-property';
 import { relativeLinks } from './rehype-plugins/relative-links';
@@ -30,29 +33,34 @@ import * as emoji from './remark-plugins/emoji';
 import { pukiwikiLikeLinker } from './remark-plugins/pukiwiki-like-linker';
 import * as xsvToTable from './remark-plugins/xsv-to-table';
 
-
 // import EasyGrid from './PreProcessor/EasyGrid';
 
-
 // eslint-disable-next-line @typescript-eslint/no-unused-vars
 const logger = loggerFactory('growi:services:renderer');
 
-
 type SanitizePlugin = PluginTuple<[SanitizeOption]>;
 
-let currentInitializedSanitizeType: RehypeSanitizeType = RehypeSanitizeType.RECOMMENDED;
+let currentInitializedSanitizeType: RehypeSanitizeType =
+  RehypeSanitizeType.RECOMMENDED;
 let commonSanitizeOption: SanitizeOption;
-export const getCommonSanitizeOption = (config:RendererConfig): SanitizeOption => {
-  if (commonSanitizeOption == null || config.sanitizeType !== currentInitializedSanitizeType) {
+export const getCommonSanitizeOption = (
+  config: RendererConfig,
+): SanitizeOption => {
+  if (
+    commonSanitizeOption == null ||
+    config.sanitizeType !== currentInitializedSanitizeType
+  ) {
     // initialize
     commonSanitizeOption = deepmerge(
       {
-        tagNames: config.sanitizeType === RehypeSanitizeType.RECOMMENDED
-          ? recommendedTagNames
-          : config.customTagWhitelist ?? recommendedTagNames,
-        attributes: config.sanitizeType === RehypeSanitizeType.RECOMMENDED
-          ? recommendedAttributes
-          : config.customAttrWhitelist ?? recommendedAttributes,
+        tagNames:
+          config.sanitizeType === RehypeSanitizeType.RECOMMENDED
+            ? recommendedTagNames
+            : (config.customTagWhitelist ?? recommendedTagNames),
+        attributes:
+          config.sanitizeType === RehypeSanitizeType.RECOMMENDED
+            ? recommendedAttributes
+            : (config.customAttrWhitelist ?? recommendedAttributes),
         clobberPrefix: '', // remove clobber prefix
       },
       codeBlock.sanitizeOption,
@@ -64,8 +72,9 @@ export const getCommonSanitizeOption = (config:RendererConfig): SanitizeOption =
   return commonSanitizeOption;
 };
 
-
-const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin => {
+const isSanitizePlugin = (
+  pluggable: Pluggable,
+): pluggable is SanitizePlugin => {
   if (!Array.isArray(pluggable) || pluggable.length < 2) {
     return false;
   }
@@ -73,7 +82,10 @@ const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin =>
   return 'tagNames' in sanitizeOption && 'attributes' in sanitizeOption;
 };
 
-const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolean): boolean => {
+const hasSanitizePlugin = (
+  options: RendererOptions,
+  shouldBeTheLastItem: boolean,
+): boolean => {
   const { rehypePlugins } = options;
   if (rehypePlugins == null || rehypePlugins.length === 0) {
     return false;
@@ -81,18 +93,25 @@ const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolea
 
   return shouldBeTheLastItem
     ? isSanitizePlugin(rehypePlugins.slice(-1)[0]) // evaluate the last one
-    : rehypePlugins.some(rehypePlugin => isSanitizePlugin(rehypePlugin));
+    : rehypePlugins.some((rehypePlugin) => isSanitizePlugin(rehypePlugin));
 };
 
-export const verifySanitizePlugin = (options: RendererOptions, shouldBeTheLastItem = true): void => {
+export const verifySanitizePlugin = (
+  options: RendererOptions,
+  shouldBeTheLastItem = true,
+): void => {
   if (hasSanitizePlugin(options, shouldBeTheLastItem)) {
     return;
   }
 
-  throw new Error('The specified options does not have sanitize plugin in \'rehypePlugins\'');
+  throw new Error(
+    "The specified options does not have sanitize plugin in 'rehypePlugins'",
+  );
 };
 
-export const generateCommonOptions = (pagePath: string|undefined): RendererOptions => {
+export const generateCommonOptions = (
+  pagePath: string | undefined,
+): RendererOptions => {
   return {
     remarkPlugins: [
       gfm,
@@ -112,9 +131,12 @@ export const generateCommonOptions = (pagePath: string|undefined): RendererOptio
       [relativeLinksByPukiwikiLikeLinker, { pagePath }],
       [relativeLinks, { pagePath }],
       raw,
-      [addClass.rehypePlugin, {
-        table: 'table table-bordered',
-      }],
+      [
+        addClass.rehypePlugin,
+        {
+          table: 'table table-bordered',
+        },
+      ],
       addInlineProperty.rehypePlugin,
     ],
     components: {
@@ -124,21 +146,16 @@ export const generateCommonOptions = (pagePath: string|undefined): RendererOptio
   };
 };
 
-
 export const generateSSRViewOptions = (
-    config: RendererConfig,
-    pagePath: string,
+  config: RendererConfig,
+  pagePath: string,
 ): RendererOptions => {
-
   const options = generateCommonOptions(pagePath);
 
   const { remarkPlugins, rehypePlugins } = options;
 
   // add remark plugins
-  remarkPlugins.push(
-    math,
-    xsvToTable.remarkPlugin,
-  );
+  remarkPlugins.push(math, xsvToTable.remarkPlugin);
 
   const isEnabledLinebreaks = config.isEnabledLinebreaks;
 
@@ -146,16 +163,13 @@ export const generateSSRViewOptions = (
     remarkPlugins.push(breaks);
   }
 
-  const rehypeSanitizePlugin: Pluggable | (() => void) = config.isEnabledXssPrevention
-    ? [sanitize, getCommonSanitizeOption(config)]
-    : () => {};
+  const rehypeSanitizePlugin: Pluggable | (() => void) =
+    config.isEnabledXssPrevention
+      ? [sanitize, getCommonSanitizeOption(config)]
+      : () => {};
 
   // add rehype plugins
-  rehypePlugins.push(
-    slug,
-    rehypeSanitizePlugin,
-    katex,
-  );
+  rehypePlugins.push(slug, rehypeSanitizePlugin, katex);
 
   // add components
   // if (components != null) {

+ 1 - 1
apps/slackbot-proxy/package.json

@@ -1,6 +1,6 @@
 {
   "name": "@growi/slackbot-proxy",
-  "version": "7.3.3-slackbot-proxy.0",
+  "version": "7.3.4-slackbot-proxy.0",
   "license": "MIT",
   "private": "true",
   "scripts": {

+ 4 - 1
biome.json

@@ -35,7 +35,10 @@
       "!apps/app/src/pages/**",
       "!apps/app/src/server/**",
       "!apps/app/src/services/**",
-      "!apps/app/src/stores/**"
+      "!apps/app/src/stores/**",
+      "!apps/app/src/styles/**",
+      "!apps/app/test-with-vite/**",
+      "!apps/app/tmp/**"
     ]
   },
   "formatter": {

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "growi",
-  "version": "7.3.3-RC.0",
+  "version": "7.3.4-RC.0",
   "description": "Team collaboration software using markdown",
   "license": "MIT",
   "private": "true",

+ 4 - 2
packages/remark-drawio/src/components/DrawioViewer.tsx

@@ -22,6 +22,7 @@ declare global {
 }
 
 export type DrawioViewerProps = {
+  isDarkMode: 'true' | 'false';
   diagramIndex: number;
   bol: number;
   eol: number;
@@ -38,6 +39,7 @@ export type DrawioEditByViewerProps = {
 
 export const DrawioViewer = memo((props: DrawioViewerProps): JSX.Element => {
   const {
+    isDarkMode,
     diagramIndex,
     bol,
     eol,
@@ -108,13 +110,13 @@ export const DrawioViewer = memo((props: DrawioViewerProps): JSX.Element => {
 
     let mxgraphData: string | undefined;
     try {
-      mxgraphData = generateMxgraphData(code);
+      mxgraphData = generateMxgraphData(code, isDarkMode === 'true');
     } catch (err) {
       setError(err);
     }
 
     return `<div class="mxgraph" data-mxgraph="${mxgraphData}"></div>`;
-  }, [children]);
+  }, [children, isDarkMode]);
 
   useEffect(() => {
     if (mxgraphHtml.length > 0) {

+ 15 - 8
packages/remark-drawio/src/services/renderer/remark-drawio.ts

@@ -4,7 +4,7 @@ import type { Code, Node, Paragraph } from 'mdast';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
-const SUPPORTED_ATTRIBUTES = ['diagramIndex', 'bol', 'eol'];
+const SUPPORTED_ATTRIBUTES = ['diagramIndex', 'bol', 'eol', 'isDarkMode'];
 
 interface Data {
   hName?: string;
@@ -17,7 +17,7 @@ function isDrawioBlock(lang?: string | null): lang is Lang {
   return /^drawio$/.test(lang ?? '');
 }
 
-function rewriteNode(node: Node, index: number) {
+function rewriteNode(node: Node, index: number, isDarkMode?: boolean) {
   node.type = 'paragraph';
   (node as Paragraph).children = [
     { type: 'text', value: (node as Code).value },
@@ -32,16 +32,23 @@ function rewriteNode(node: Node, index: number) {
     diagramIndex: index,
     bol: node.position?.start.line,
     eol: node.position?.end.line,
+    isDarkMode: isDarkMode ? 'true' : 'false',
     key: `drawio-${index}`,
   };
 }
 
-export const remarkPlugin: Plugin = () => (tree) => {
-  visit(tree, 'code', (node: Code, index) => {
-    if (isDrawioBlock(node.lang)) {
-      rewriteNode(node, index ?? 0);
-    }
-  });
+type DrawioRemarkPlugin = {
+  isDarkMode?: boolean;
+};
+
+export const remarkPlugin: Plugin<[DrawioRemarkPlugin]> = (options) => {
+  return (tree) => {
+    visit(tree, 'code', (node: Code, index) => {
+      if (isDrawioBlock(node.lang)) {
+        rewriteNode(node, index ?? 0, options.isDarkMode);
+      }
+    });
+  };
 };
 
 export const sanitizeOption: SanitizeOption = {

+ 7 - 2
packages/remark-drawio/src/utils/embed.ts

@@ -53,7 +53,10 @@ const escapeHTML = (string): string => {
   });
 };
 
-export const generateMxgraphData = (code: string): string => {
+export const generateMxgraphData = (
+  code: string,
+  isDarkMode: boolean,
+): string => {
   const trimedCode = code.trim();
   if (!trimedCode) {
     return '';
@@ -82,7 +85,9 @@ export const generateMxgraphData = (code: string): string => {
     resize: true,
     lightbox: 'false',
     xml,
-    'dark-mode': 'auto',
+    // To sync with GROWI app's color mode, pass 'dark' when the app is in dark mode. 'auto' would read OS color scheme via window.matchMedia instead.
+    // refs: https://github.com/jgraph/drawio/blob/eaae294cba5010e3a9d04b685407e79512f88d2d/src/main/webapp/js/diagramly/GraphViewer.js#L888-L892
+    'dark-mode': isDarkMode ? 'dark' : undefined,
   };
 
   return escapeHTML(JSON.stringify(mxGraphData));