AppContainer.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import { Container } from 'unstated';
  2. import axios from 'axios';
  3. import InterceptorManager from '@commons/service/interceptor-manager';
  4. import emojiStrategy from '../util/emojione/emoji_strategy_shrinked.json';
  5. import GrowiRenderer from '../util/GrowiRenderer';
  6. import {
  7. DetachCodeBlockInterceptor,
  8. RestoreCodeBlockInterceptor,
  9. } from '../util/interceptor/detach-code-blocks';
  10. import i18nFactory from '../util/i18n';
  11. /**
  12. * Service container related to options for Application
  13. * @extends {Container} unstated Container
  14. */
  15. export default class AppContainer extends Container {
  16. constructor() {
  17. super();
  18. this.state = {
  19. editorMode: null,
  20. };
  21. const body = document.querySelector('body');
  22. this.me = body.dataset.currentUsername;
  23. this.isAdmin = body.dataset.isAdmin === 'true';
  24. this.csrfToken = body.dataset.csrftoken;
  25. this.isPluginEnabled = body.dataset.pluginEnabled === 'true';
  26. this.isLoggedin = document.querySelector('.main-container.nologin') == null;
  27. this.config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
  28. const userAgent = window.navigator.userAgent.toLowerCase();
  29. this.isMobile = /iphone|ipad|android/.test(userAgent);
  30. this.isDocSaved = true;
  31. this.originRenderer = new GrowiRenderer(this);
  32. this.interceptorManager = new InterceptorManager();
  33. this.interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(this), 10); // process as soon as possible
  34. this.interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(this), 900); // process as late as possible
  35. const userlang = body.dataset.userlang;
  36. this.i18n = i18nFactory(userlang);
  37. this.users = [];
  38. this.userByName = {};
  39. this.userById = {};
  40. this.recoverData();
  41. if (this.isLoggedin) {
  42. this.fetchUsers();
  43. }
  44. this.containerInstances = {};
  45. this.componentInstances = {};
  46. this.rendererInstances = {};
  47. this.fetchUsers = this.fetchUsers.bind(this);
  48. this.apiGet = this.apiGet.bind(this);
  49. this.apiPost = this.apiPost.bind(this);
  50. this.apiRequest = this.apiRequest.bind(this);
  51. }
  52. /**
  53. * Workaround for the mangling in production build to break constructor.name
  54. */
  55. static getClassName() {
  56. return 'AppContainer';
  57. }
  58. initPlugins() {
  59. if (this.isPluginEnabled) {
  60. const growiPlugin = window.growiPlugin;
  61. growiPlugin.installAll(this, this.originRenderer);
  62. }
  63. }
  64. injectToWindow() {
  65. window.appContainer = this;
  66. const originRenderer = this.getOriginRenderer();
  67. window.growiRenderer = originRenderer;
  68. // backward compatibility
  69. window.crowi = this;
  70. window.crowiRenderer = originRenderer;
  71. window.crowiPlugin = window.growiPlugin;
  72. }
  73. /**
  74. * @return {Object} window.Crowi (js/legacy/crowi.js)
  75. */
  76. getCrowiForJquery() {
  77. return window.Crowi;
  78. }
  79. getConfig() {
  80. return this.config;
  81. }
  82. /**
  83. * Register unstated container instance
  84. * @param {object} instance unstated container instance
  85. */
  86. registerContainer(instance) {
  87. if (instance == null) {
  88. throw new Error('The specified instance must not be null');
  89. }
  90. const className = instance.constructor.getClassName();
  91. if (this.containerInstances[className] != null) {
  92. throw new Error('The specified instance couldn\'t register because the same type object has already been registered');
  93. }
  94. this.containerInstances[className] = instance;
  95. }
  96. /**
  97. * Get registered unstated container instance
  98. * !! THIS METHOD SHOULD ONLY BE USED FROM unstated CONTAINERS !!
  99. * !! From component instances, inject containers with `import { Subscribe } from 'unstated'` !!
  100. *
  101. * @param {string} className
  102. */
  103. getContainer(className) {
  104. return this.containerInstances[className];
  105. }
  106. /**
  107. * Register React component instance
  108. * @param {string} id
  109. * @param {object} instance React component instance
  110. */
  111. registerComponentInstance(id, instance) {
  112. if (instance == null) {
  113. throw new Error('The specified instance must not be null');
  114. }
  115. if (this.componentInstances[id] != null) {
  116. throw new Error('The specified instance couldn\'t register because the same id has already been registered');
  117. }
  118. this.componentInstances[id] = instance;
  119. }
  120. /**
  121. * Get registered React component instance
  122. * @param {string} id
  123. */
  124. getComponentInstance(id) {
  125. return this.componentInstances[id];
  126. }
  127. getOriginRenderer() {
  128. return this.originRenderer;
  129. }
  130. /**
  131. * factory method
  132. */
  133. getRenderer(mode) {
  134. if (this.rendererInstances[mode] != null) {
  135. return this.rendererInstances[mode];
  136. }
  137. const renderer = new GrowiRenderer(this, this.originRenderer);
  138. // setup
  139. renderer.initMarkdownItConfigurers(mode);
  140. renderer.setup(mode);
  141. // register
  142. this.rendererInstances[mode] = renderer;
  143. return renderer;
  144. }
  145. getEmojiStrategy() {
  146. return emojiStrategy;
  147. }
  148. recoverData() {
  149. const keys = [
  150. 'userByName',
  151. 'userById',
  152. 'users',
  153. ];
  154. keys.forEach((key) => {
  155. const keyContent = window.localStorage[key];
  156. if (keyContent) {
  157. try {
  158. this[key] = JSON.parse(keyContent);
  159. }
  160. catch (e) {
  161. window.localStorage.removeItem(key);
  162. }
  163. }
  164. });
  165. }
  166. fetchUsers() {
  167. const interval = 1000 * 60 * 15; // 15min
  168. const currentTime = new Date();
  169. if (window.localStorage.lastFetched && interval > currentTime - new Date(window.localStorage.lastFetched)) {
  170. return;
  171. }
  172. this.apiGet('/users.list', {})
  173. .then((data) => {
  174. this.users = data.users;
  175. window.localStorage.users = JSON.stringify(data.users);
  176. const userByName = {};
  177. const userById = {};
  178. for (let i = 0; i < data.users.length; i++) {
  179. const user = data.users[i];
  180. userByName[user.username] = user;
  181. userById[user._id] = user;
  182. }
  183. this.userByName = userByName;
  184. window.localStorage.userByName = JSON.stringify(userByName);
  185. this.userById = userById;
  186. window.localStorage.userById = JSON.stringify(userById);
  187. window.localStorage.lastFetched = new Date();
  188. })
  189. .catch((err) => {
  190. window.localStorage.removeItem('lastFetched');
  191. // ignore errors
  192. });
  193. }
  194. findUserById(userId) {
  195. if (this.userById && this.userById[userId]) {
  196. return this.userById[userId];
  197. }
  198. return null;
  199. }
  200. findUserByIds(userIds) {
  201. const users = [];
  202. for (const userId of userIds) {
  203. const user = this.findUserById(userId);
  204. if (user) {
  205. users.push(user);
  206. }
  207. }
  208. return users;
  209. }
  210. findUser(username) {
  211. if (this.userByName && this.userByName[username]) {
  212. return this.userByName[username];
  213. }
  214. return null;
  215. }
  216. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  217. let targetComponent;
  218. switch (componentKind) {
  219. case 'page':
  220. targetComponent = this.getComponentInstance('Page');
  221. break;
  222. }
  223. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  224. }
  225. apiGet(path, params) {
  226. return this.apiRequest('get', path, { params });
  227. }
  228. apiPost(path, params) {
  229. if (!params._csrf) {
  230. params._csrf = this.csrfToken;
  231. }
  232. return this.apiRequest('post', path, params);
  233. }
  234. apiRequest(method, path, params) {
  235. return new Promise((resolve, reject) => {
  236. axios[method](`/_api${path}`, params)
  237. .then((res) => {
  238. if (res.data.ok) {
  239. resolve(res.data);
  240. }
  241. else {
  242. reject(new Error(res.data.error));
  243. }
  244. })
  245. .catch((res) => {
  246. reject(res);
  247. });
  248. });
  249. }
  250. }