AppContainer.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. mediaQueryListForDarkMode,
  9. applyColorScheme,
  10. savePreferenceByUser,
  11. } from '../util/color-scheme';
  12. import Apiv1ErrorHandler from '../util/apiv1ErrorHandler';
  13. import {
  14. DetachCodeBlockInterceptor,
  15. RestoreCodeBlockInterceptor,
  16. } from '../util/interceptor/detach-code-blocks';
  17. import {
  18. DrawioInterceptor,
  19. } from '../util/interceptor/drawio-interceptor';
  20. import i18nFactory from '../util/i18n';
  21. import apiv3ErrorHandler from '../util/apiv3ErrorHandler';
  22. /**
  23. * Service container related to options for Application
  24. * @extends {Container} unstated Container
  25. */
  26. export default class AppContainer extends Container {
  27. constructor() {
  28. super();
  29. this.state = {
  30. // stetes for contents
  31. recentlyUpdatedPages: [],
  32. };
  33. const body = document.querySelector('body');
  34. this.csrfToken = body.dataset.csrftoken;
  35. this.isLoggedin = document.querySelector('body.nologin') == null;
  36. this.config = JSON.parse(document.getElementById('growi-context-hydrate').textContent || '{}');
  37. const userAgent = window.navigator.userAgent.toLowerCase();
  38. this.isMobile = /iphone|ipad|android/.test(userAgent);
  39. const userlang = body.dataset.userlang;
  40. this.i18n = i18nFactory(userlang);
  41. this.containerInstances = {};
  42. this.componentInstances = {};
  43. this.rendererInstances = {};
  44. this.apiGet = this.apiGet.bind(this);
  45. this.apiPost = this.apiPost.bind(this);
  46. this.apiDelete = this.apiDelete.bind(this);
  47. this.apiRequest = this.apiRequest.bind(this);
  48. this.apiv3Root = '/_api/v3';
  49. this.apiv3 = {
  50. get: this.apiv3Get.bind(this),
  51. post: this.apiv3Post.bind(this),
  52. put: this.apiv3Put.bind(this),
  53. delete: this.apiv3Delete.bind(this),
  54. };
  55. }
  56. /**
  57. * Workaround for the mangling in production build to break constructor.name
  58. */
  59. static getClassName() {
  60. return 'AppContainer';
  61. }
  62. initApp() {
  63. this.initMediaQueryForColorScheme();
  64. this.injectToWindow();
  65. }
  66. initContents() {
  67. const body = document.querySelector('body');
  68. const currentUserElem = document.getElementById('growi-current-user');
  69. if (currentUserElem != null) {
  70. this.currentUser = JSON.parse(currentUserElem.textContent);
  71. }
  72. this.isAdmin = body.dataset.isAdmin === 'true';
  73. this.isDocSaved = true;
  74. this.originRenderer = new GrowiRenderer(this);
  75. this.interceptorManager = new InterceptorManager();
  76. this.interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(this), 10); // process as soon as possible
  77. this.interceptorManager.addInterceptor(new DrawioInterceptor(this), 20);
  78. this.interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(this), 900); // process as late as possible
  79. if (this.isLoggedin) {
  80. // remove old user cache
  81. this.removeOldUserCache();
  82. }
  83. const isPluginEnabled = body.dataset.pluginEnabled === 'true';
  84. if (isPluginEnabled) {
  85. this.initPlugins();
  86. }
  87. this.injectToWindow();
  88. }
  89. async initMediaQueryForColorScheme() {
  90. const switchStateByMediaQuery = async(mql) => {
  91. const preferDarkMode = mql.matches;
  92. this.setState({ preferDarkModeByMediaQuery: preferDarkMode });
  93. applyColorScheme();
  94. };
  95. // add event listener
  96. mediaQueryListForDarkMode.addListener(switchStateByMediaQuery);
  97. }
  98. initPlugins() {
  99. const growiPlugin = window.growiPlugin;
  100. growiPlugin.installAll(this, this.originRenderer);
  101. }
  102. injectToWindow() {
  103. window.appContainer = this;
  104. const originRenderer = this.getOriginRenderer();
  105. window.growiRenderer = originRenderer;
  106. // backward compatibility
  107. window.crowi = this;
  108. window.crowiRenderer = originRenderer;
  109. window.crowiPlugin = window.growiPlugin;
  110. }
  111. get currentUserId() {
  112. if (this.currentUser == null) {
  113. return null;
  114. }
  115. return this.currentUser._id;
  116. }
  117. get currentUsername() {
  118. if (this.currentUser == null) {
  119. return null;
  120. }
  121. return this.currentUser.username;
  122. }
  123. /**
  124. * @return {Object} window.Crowi (js/legacy/crowi.js)
  125. */
  126. getCrowiForJquery() {
  127. return window.Crowi;
  128. }
  129. getConfig() {
  130. return this.config;
  131. }
  132. /**
  133. * Register unstated container instance
  134. * @param {object} instance unstated container instance
  135. */
  136. registerContainer(instance) {
  137. if (instance == null) {
  138. throw new Error('The specified instance must not be null');
  139. }
  140. const className = instance.constructor.getClassName();
  141. if (this.containerInstances[className] != null) {
  142. throw new Error('The specified instance couldn\'t register because the same type object has already been registered');
  143. }
  144. this.containerInstances[className] = instance;
  145. }
  146. /**
  147. * Get registered unstated container instance
  148. * !! THIS METHOD SHOULD ONLY BE USED FROM unstated CONTAINERS !!
  149. * !! From component instances, inject containers with `import { Subscribe } from 'unstated'` !!
  150. *
  151. * @param {string} className
  152. */
  153. getContainer(className) {
  154. return this.containerInstances[className];
  155. }
  156. /**
  157. * Register React component instance
  158. * @param {string} id
  159. * @param {object} instance React component instance
  160. */
  161. registerComponentInstance(id, instance) {
  162. if (instance == null) {
  163. throw new Error('The specified instance must not be null');
  164. }
  165. if (this.componentInstances[id] != null) {
  166. throw new Error('The specified instance couldn\'t register because the same id has already been registered');
  167. }
  168. this.componentInstances[id] = instance;
  169. }
  170. /**
  171. * Get registered React component instance
  172. * @param {string} id
  173. */
  174. getComponentInstance(id) {
  175. return this.componentInstances[id];
  176. }
  177. /**
  178. *
  179. * @param {string} breakpoint id of breakpoint
  180. * @param {function} handler event handler for media query
  181. * @param {boolean} invokeOnInit invoke handler after the initialization if true
  182. */
  183. addBreakpointListener(breakpoint, handler, invokeOnInit = false) {
  184. document.addEventListener('DOMContentLoaded', () => {
  185. // get the value of '--breakpoint-*'
  186. const breakpointPixel = parseInt(window.getComputedStyle(document.documentElement).getPropertyValue(`--breakpoint-${breakpoint}`), 10);
  187. const mediaQuery = window.matchMedia(`(min-width: ${breakpointPixel}px)`);
  188. // add event listener
  189. mediaQuery.addListener(handler);
  190. // initialize
  191. if (invokeOnInit) {
  192. handler(mediaQuery);
  193. }
  194. });
  195. }
  196. getOriginRenderer() {
  197. return this.originRenderer;
  198. }
  199. /**
  200. * factory method
  201. */
  202. getRenderer(mode) {
  203. if (this.rendererInstances[mode] != null) {
  204. return this.rendererInstances[mode];
  205. }
  206. const renderer = new GrowiRenderer(this, this.originRenderer);
  207. // setup
  208. renderer.initMarkdownItConfigurers(mode);
  209. renderer.setup(mode);
  210. // register
  211. this.rendererInstances[mode] = renderer;
  212. return renderer;
  213. }
  214. getEmojiStrategy() {
  215. return emojiStrategy;
  216. }
  217. removeOldUserCache() {
  218. if (window.localStorage.userByName == null) {
  219. return;
  220. }
  221. const keys = ['userByName', 'userById', 'users', 'lastFetched'];
  222. keys.forEach((key) => {
  223. window.localStorage.removeItem(key);
  224. });
  225. }
  226. async retrieveRecentlyUpdated() {
  227. const { data } = await this.apiv3Get('/pages/recent');
  228. this.setState({ recentlyUpdatedPages: data.pages });
  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. launchDrawioModal(componentKind, beginLineNumber, endLineNumber) {
  240. let targetComponent;
  241. switch (componentKind) {
  242. case 'page':
  243. targetComponent = this.getComponentInstance('Page');
  244. break;
  245. }
  246. targetComponent.launchDrawioModal(beginLineNumber, endLineNumber);
  247. }
  248. /**
  249. * Set color scheme preference by user
  250. * @param {boolean} isDarkMode
  251. */
  252. async setColorSchemePreference(isDarkMode) {
  253. this.setState({ preferDarkModeByUser: isDarkMode });
  254. savePreferenceByUser(isDarkMode);
  255. applyColorScheme();
  256. }
  257. async apiGet(path, params) {
  258. return this.apiRequest('get', path, { params });
  259. }
  260. async apiPost(path, params) {
  261. if (!params._csrf) {
  262. params._csrf = this.csrfToken;
  263. }
  264. return this.apiRequest('post', path, params);
  265. }
  266. async apiDelete(path, params) {
  267. if (!params._csrf) {
  268. params._csrf = this.csrfToken;
  269. }
  270. return this.apiRequest('delete', path, { data: params });
  271. }
  272. async apiRequest(method, path, params) {
  273. const res = await axios[method](`/_api${path}`, params);
  274. if (res.data.ok) {
  275. return res.data;
  276. }
  277. // Return error code if code is exist
  278. if (res.data.code != null) {
  279. const error = new Apiv1ErrorHandler(res.data.error, res.data.code);
  280. throw error;
  281. }
  282. throw new Error(res.data.error);
  283. }
  284. async apiv3Request(method, path, params) {
  285. try {
  286. const res = await axios[method](urljoin(this.apiv3Root, path), params);
  287. return res.data;
  288. }
  289. catch (err) {
  290. const errors = apiv3ErrorHandler(err);
  291. throw errors;
  292. }
  293. }
  294. async apiv3Get(path, params) {
  295. return this.apiv3Request('get', path, { params });
  296. }
  297. async apiv3Post(path, params = {}) {
  298. if (!params._csrf) {
  299. params._csrf = this.csrfToken;
  300. }
  301. return this.apiv3Request('post', path, params);
  302. }
  303. async apiv3Put(path, params = {}) {
  304. if (!params._csrf) {
  305. params._csrf = this.csrfToken;
  306. }
  307. return this.apiv3Request('put', path, params);
  308. }
  309. async apiv3Delete(path, params = {}) {
  310. if (!params._csrf) {
  311. params._csrf = this.csrfToken;
  312. }
  313. return this.apiv3Request('delete', path, { params });
  314. }
  315. }