AppContainer.js 8.9 KB

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