AppContainer.js 9.3 KB

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