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

convert util/Crowi to an unstated container

Yuki Takei 6 лет назад
Родитель
Сommit
65cc1fd1ad

+ 9 - 11
src/client/js/app.js

@@ -12,8 +12,6 @@ import * as entities from 'entities';
 import i18nFactory from './i18n';
 
 
-import Crowi from './util/Crowi';
-// import CrowiRenderer from './util/CrowiRenderer';
 import GrowiRenderer from './util/GrowiRenderer';
 
 import HeaderSearchBox from './components/HeaderSearchBox';
@@ -47,6 +45,7 @@ import CustomHeaderEditor from './components/Admin/CustomHeaderEditor';
 import AdminRebuildSearch from './components/Admin/AdminRebuildSearch';
 import GroupDeleteModal from './components/GroupDeleteModal/GroupDeleteModal';
 
+import AppContextContainer from './services/AppContextContainer';
 import PageContainer from './services/PageContainer';
 import CommentContainer from './components/PageComment/CommentContainer';
 import EditorContainer from './services/EditorContainer';
@@ -96,17 +95,16 @@ if (mainContent !== null) {
 }
 const isLoggedin = document.querySelector('.main-container.nologin') == null;
 
-// FIXME
-const crowi = new Crowi({
-  me: $('body').data('current-username'),
-  isAdmin: $('body').data('is-admin'),
-  csrfToken: $('body').data('csrftoken'),
-}, window);
-window.crowi = crowi;
-crowi.setConfig(JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}'));
+const appContextContainer = new AppContextContainer();
+
+// backward compatibility
+const crowi = appContextContainer;
+window.crowi = appContextContainer;
+
 if (isLoggedin) {
-  crowi.fetchUsers();
+  appContextContainer.fetchUsers();
 }
+
 const socket = crowi.getWebSocket();
 const socketClientId = crowi.getSocketClientId();
 

+ 1 - 1
src/client/js/components/MyDraftList/MyDraftList.jsx

@@ -29,7 +29,7 @@ export default class MyDraftList extends React.Component {
   }
 
   async getDraftsFromLocalStorage() {
-    const draftsAsObj = JSON.parse(this.props.crowi.localStorage.getItem('draft') || '{}');
+    const draftsAsObj = JSON.parse(window.localStorage.getItem('draft') || '{}');
 
     const res = await this.props.crowi.apiGet('/pages.exist', {
       pages: draftsAsObj,

+ 2 - 2
src/client/js/components/PageEditor.js

@@ -62,11 +62,11 @@ export default class PageEditor extends React.Component {
     // initial rendering
     this.renderPreview(this.state.markdown);
 
-    this.props.crowi.window.addEventListener('beforeunload', this.showUnsavedWarning);
+    window.addEventListener('beforeunload', this.showUnsavedWarning);
   }
 
   componentWillUnmount() {
-    this.props.crowi.window.removeEventListener('beforeunload', this.showUnsavedWarning);
+    window.removeEventListener('beforeunload', this.showUnsavedWarning);
   }
 
   showUnsavedWarning(e) {

+ 29 - 33
src/client/js/util/Crowi.js → src/client/js/services/AppContextContainer.js

@@ -1,32 +1,37 @@
-/**
- * Crowi context class for client
- */
+import { Container } from 'unstated';
 
 import axios from 'axios';
 import io from 'socket.io-client';
 
 import InterceptorManager from '@commons/service/interceptor-manager';
 
-import emojiStrategy from './emojione/emoji_strategy_shrinked.json';
+import emojiStrategy from '../util/emojione/emoji_strategy_shrinked.json';
 
 import {
   DetachCodeBlockInterceptor,
   RestoreCodeBlockInterceptor,
-} from './interceptor/detach-code-blocks';
+} from '../util/interceptor/detach-code-blocks';
+
+/**
+ * Service container related to options for Application
+ * @extends {Container} unstated Container
+ */
+export default class AppContextContainer extends Container {
 
-export default class Crowi {
+  constructor() {
+    super();
 
-  constructor(context, window) {
-    this.context = context;
-    this.config = {};
+    const body = document.querySelector('body');
+
+    this.me = body.dataset.currentUsername;
+    this.isAdmin = body.dataset.isAdmin;
+    this.csrfToken = body.dataset.csrftoken;
+
+    this.config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
 
     const userAgent = window.navigator.userAgent.toLowerCase();
     this.isMobile = /iphone|ipad|android/.test(userAgent);
 
-    this.window = window;
-    this.location = window.location || {};
-    this.document = window.document || {};
-    this.localStorage = window.localStorage || {};
     this.socketClientId = Math.floor(Math.random() * 100000);
     this.page = undefined;
     this.pageEditor = undefined;
@@ -41,11 +46,6 @@ export default class Crowi {
     this.interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(this), 10); // process as soon as possible
     this.interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(this), 900); // process as late as possible
 
-    // FIXME
-    this.me = context.me;
-    this.isAdmin = context.isAdmin;
-    this.csrfToken = context.csrfToken;
-
     this.users = [];
     this.userByName = {};
     this.userById = {};
@@ -64,10 +64,6 @@ export default class Crowi {
     return window.Crowi;
   }
 
-  setConfig(config) {
-    this.config = config;
-  }
-
   getConfig() {
     return this.config;
   }
@@ -109,13 +105,13 @@ export default class Crowi {
     ];
 
     keys.forEach((key) => {
-      const keyContent = this.localStorage[key];
+      const keyContent = window.localStorage[key];
       if (keyContent) {
         try {
           this[key] = JSON.parse(keyContent);
         }
         catch (e) {
-          this.localStorage.removeItem(key);
+          window.localStorage.removeItem(key);
         }
       }
     });
@@ -124,14 +120,14 @@ export default class Crowi {
   fetchUsers() {
     const interval = 1000 * 60 * 15; // 15min
     const currentTime = new Date();
-    if (this.localStorage.lastFetched && interval > currentTime - new Date(this.localStorage.lastFetched)) {
+    if (window.localStorage.lastFetched && interval > currentTime - new Date(window.localStorage.lastFetched)) {
       return;
     }
 
     this.apiGet('/users.list', {})
       .then((data) => {
         this.users = data.users;
-        this.localStorage.users = JSON.stringify(data.users);
+        window.localStorage.users = JSON.stringify(data.users);
 
         const userByName = {};
         const userById = {};
@@ -141,15 +137,15 @@ export default class Crowi {
           userById[user._id] = user;
         }
         this.userByName = userByName;
-        this.localStorage.userByName = JSON.stringify(userByName);
+        window.localStorage.userByName = JSON.stringify(userByName);
 
         this.userById = userById;
-        this.localStorage.userById = JSON.stringify(userById);
+        window.localStorage.userById = JSON.stringify(userById);
 
-        this.localStorage.lastFetched = new Date();
+        window.localStorage.lastFetched = new Date();
       })
       .catch((err) => {
-        this.localStorage.removeItem('lastFetched');
+        window.localStorage.removeItem('lastFetched');
       // ignore errors
       });
   }
@@ -168,16 +164,16 @@ export default class Crowi {
 
   clearDraft(path) {
     delete this.draft[path];
-    this.localStorage.setItem('draft', JSON.stringify(this.draft));
+    window.localStorage.setItem('draft', JSON.stringify(this.draft));
   }
 
   clearAllDrafts() {
-    this.localStorage.removeItem('draft');
+    window.localStorage.removeItem('draft');
   }
 
   saveDraft(path, body) {
     this.draft[path] = body;
-    this.localStorage.setItem('draft', JSON.stringify(this.draft));
+    window.localStorage.setItem('draft', JSON.stringify(this.draft));
   }
 
   findDraft(path) {

+ 5 - 2
src/client/js/util/PostProcessor/CrowiTemplate.js

@@ -3,6 +3,10 @@ import dateFnsFormat from 'date-fns/format';
 export default class CrowiTemplate {
 
   constructor(crowi) {
+    this.crowi = crowi;
+
+    this.getUser = this.getUser.bind(this);
+
     this.templatePattern = {
       year: this.getYear,
       month: this.getMonth,
@@ -54,8 +58,7 @@ export default class CrowiTemplate {
   }
 
   getUser() {
-    // FIXME
-    const username = window.crowi.me || null;
+    const username = this.crowi.me || null;
 
     if (!username) {
       return '';