AppContainer.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. fetchUsers() {
  177. const interval = 1000 * 60 * 15; // 15min
  178. const currentTime = new Date();
  179. if (window.localStorage.lastFetched && interval > currentTime - new Date(window.localStorage.lastFetched)) {
  180. return;
  181. }
  182. this.apiGet('/users.list', {})
  183. .then((data) => {
  184. this.users = data.users;
  185. window.localStorage.users = JSON.stringify(data.users);
  186. const userByName = {};
  187. const userById = {};
  188. for (let i = 0; i < data.users.length; i++) {
  189. const user = data.users[i];
  190. userByName[user.username] = user;
  191. userById[user._id] = user;
  192. }
  193. this.userByName = userByName;
  194. window.localStorage.userByName = JSON.stringify(userByName);
  195. this.userById = userById;
  196. window.localStorage.userById = JSON.stringify(userById);
  197. window.localStorage.lastFetched = new Date();
  198. })
  199. .catch((err) => {
  200. window.localStorage.removeItem('lastFetched');
  201. // ignore errors
  202. });
  203. }
  204. findUserById(userId) {
  205. if (this.userById && this.userById[userId]) {
  206. return this.userById[userId];
  207. }
  208. return null;
  209. }
  210. findUserByIds(userIds) {
  211. const users = [];
  212. for (const userId of userIds) {
  213. const user = this.findUserById(userId);
  214. if (user) {
  215. users.push(user);
  216. }
  217. }
  218. return users;
  219. }
  220. findUser(username) {
  221. if (this.userByName && this.userByName[username]) {
  222. return this.userByName[username];
  223. }
  224. return null;
  225. }
  226. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  227. let targetComponent;
  228. switch (componentKind) {
  229. case 'page':
  230. targetComponent = this.getComponentInstance('Page');
  231. break;
  232. }
  233. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  234. }
  235. async apiGet(path, params) {
  236. return this.apiRequest('get', path, { params });
  237. }
  238. async apiPost(path, params) {
  239. if (!params._csrf) {
  240. params._csrf = this.csrfToken;
  241. }
  242. return this.apiRequest('post', path, params);
  243. }
  244. async apiDelete(path, params) {
  245. if (!params._csrf) {
  246. params._csrf = this.csrfToken;
  247. }
  248. return this.apiRequest('delete', path, { data: params });
  249. }
  250. async apiRequest(method, path, params) {
  251. const res = await axios[method](`/_api${path}`, params);
  252. if (res.data.ok) {
  253. return res.data;
  254. }
  255. throw new Error(res.data.error);
  256. }
  257. async apiv3Request(method, path, params) {
  258. try {
  259. const res = await axios[method](urljoin(this.apiv3Root, path), params);
  260. return res.data;
  261. }
  262. catch (err) {
  263. const errors = apiv3ErrorHandler(err);
  264. throw errors;
  265. }
  266. }
  267. async apiv3Get(path, params) {
  268. return this.apiv3Request('get', path, { params });
  269. }
  270. async apiv3Post(path, params = {}) {
  271. if (!params._csrf) {
  272. params._csrf = this.csrfToken;
  273. }
  274. return this.apiv3Request('post', path, params);
  275. }
  276. async apiv3Put(path, params = {}) {
  277. if (!params._csrf) {
  278. params._csrf = this.csrfToken;
  279. }
  280. return this.apiv3Request('put', path, params);
  281. }
  282. async apiv3Delete(path, params = {}) {
  283. if (!params._csrf) {
  284. params._csrf = this.csrfToken;
  285. }
  286. return this.apiv3Request('delete', path, { params });
  287. }
  288. }