AppContainer.js 9.0 KB

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