AppContainer.js 7.7 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 || null; // will be initialized with null when data is empty string
  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.apiDelete = this.apiDelete.bind(this);
  51. this.apiRequest = this.apiRequest.bind(this);
  52. }
  53. /**
  54. * Workaround for the mangling in production build to break constructor.name
  55. */
  56. static getClassName() {
  57. return 'AppContainer';
  58. }
  59. initPlugins() {
  60. if (this.isPluginEnabled) {
  61. const growiPlugin = window.growiPlugin;
  62. growiPlugin.installAll(this, this.originRenderer);
  63. }
  64. }
  65. injectToWindow() {
  66. window.appContainer = this;
  67. const originRenderer = this.getOriginRenderer();
  68. window.growiRenderer = originRenderer;
  69. // backward compatibility
  70. window.crowi = this;
  71. window.crowiRenderer = originRenderer;
  72. window.crowiPlugin = window.growiPlugin;
  73. }
  74. /**
  75. * @return {Object} window.Crowi (js/legacy/crowi.js)
  76. */
  77. getCrowiForJquery() {
  78. return window.Crowi;
  79. }
  80. getConfig() {
  81. return this.config;
  82. }
  83. /**
  84. * Register unstated container instance
  85. * @param {object} instance unstated container instance
  86. */
  87. registerContainer(instance) {
  88. if (instance == null) {
  89. throw new Error('The specified instance must not be null');
  90. }
  91. const className = instance.constructor.getClassName();
  92. if (this.containerInstances[className] != null) {
  93. throw new Error('The specified instance couldn\'t register because the same type object has already been registered');
  94. }
  95. this.containerInstances[className] = instance;
  96. }
  97. /**
  98. * Get registered unstated container instance
  99. * !! THIS METHOD SHOULD ONLY BE USED FROM unstated CONTAINERS !!
  100. * !! From component instances, inject containers with `import { Subscribe } from 'unstated'` !!
  101. *
  102. * @param {string} className
  103. */
  104. getContainer(className) {
  105. return this.containerInstances[className];
  106. }
  107. /**
  108. * Register React component instance
  109. * @param {string} id
  110. * @param {object} instance React component instance
  111. */
  112. registerComponentInstance(id, instance) {
  113. if (instance == null) {
  114. throw new Error('The specified instance must not be null');
  115. }
  116. if (this.componentInstances[id] != null) {
  117. throw new Error('The specified instance couldn\'t register because the same id has already been registered');
  118. }
  119. this.componentInstances[id] = instance;
  120. }
  121. /**
  122. * Get registered React component instance
  123. * @param {string} id
  124. */
  125. getComponentInstance(id) {
  126. return this.componentInstances[id];
  127. }
  128. getOriginRenderer() {
  129. return this.originRenderer;
  130. }
  131. /**
  132. * factory method
  133. */
  134. getRenderer(mode) {
  135. if (this.rendererInstances[mode] != null) {
  136. return this.rendererInstances[mode];
  137. }
  138. const renderer = new GrowiRenderer(this, this.originRenderer);
  139. // setup
  140. renderer.initMarkdownItConfigurers(mode);
  141. renderer.setup(mode);
  142. // register
  143. this.rendererInstances[mode] = renderer;
  144. return renderer;
  145. }
  146. getEmojiStrategy() {
  147. return emojiStrategy;
  148. }
  149. recoverData() {
  150. const keys = [
  151. 'userByName',
  152. 'userById',
  153. 'users',
  154. ];
  155. keys.forEach((key) => {
  156. const keyContent = window.localStorage[key];
  157. if (keyContent) {
  158. try {
  159. this[key] = JSON.parse(keyContent);
  160. }
  161. catch (e) {
  162. window.localStorage.removeItem(key);
  163. }
  164. }
  165. });
  166. }
  167. fetchUsers() {
  168. const interval = 1000 * 60 * 15; // 15min
  169. const currentTime = new Date();
  170. if (window.localStorage.lastFetched && interval > currentTime - new Date(window.localStorage.lastFetched)) {
  171. return;
  172. }
  173. this.apiGet('/users.list', {})
  174. .then((data) => {
  175. this.users = data.users;
  176. window.localStorage.users = JSON.stringify(data.users);
  177. const userByName = {};
  178. const userById = {};
  179. for (let i = 0; i < data.users.length; i++) {
  180. const user = data.users[i];
  181. userByName[user.username] = user;
  182. userById[user._id] = user;
  183. }
  184. this.userByName = userByName;
  185. window.localStorage.userByName = JSON.stringify(userByName);
  186. this.userById = userById;
  187. window.localStorage.userById = JSON.stringify(userById);
  188. window.localStorage.lastFetched = new Date();
  189. })
  190. .catch((err) => {
  191. window.localStorage.removeItem('lastFetched');
  192. // ignore errors
  193. });
  194. }
  195. findUserById(userId) {
  196. if (this.userById && this.userById[userId]) {
  197. return this.userById[userId];
  198. }
  199. return null;
  200. }
  201. findUserByIds(userIds) {
  202. const users = [];
  203. for (const userId of userIds) {
  204. const user = this.findUserById(userId);
  205. if (user) {
  206. users.push(user);
  207. }
  208. }
  209. return users;
  210. }
  211. findUser(username) {
  212. if (this.userByName && this.userByName[username]) {
  213. return this.userByName[username];
  214. }
  215. return null;
  216. }
  217. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  218. let targetComponent;
  219. switch (componentKind) {
  220. case 'page':
  221. targetComponent = this.getComponentInstance('Page');
  222. break;
  223. }
  224. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  225. }
  226. async apiGet(path, params) {
  227. return this.apiRequest('get', path, { params });
  228. }
  229. async apiPost(path, params) {
  230. if (!params._csrf) {
  231. params._csrf = this.csrfToken;
  232. }
  233. return this.apiRequest('post', path, params);
  234. }
  235. async apiDelete(path, params) {
  236. if (!params._csrf) {
  237. params._csrf = this.csrfToken;
  238. }
  239. return this.apiRequest('delete', path, { data: params });
  240. }
  241. async apiRequest(method, path, params) {
  242. const res = await axios[method](`/_api${path}`, params);
  243. if (res.data.ok) {
  244. return res.data;
  245. }
  246. throw new Error(res.data.error);
  247. }
  248. }