AppContainer.js 9.2 KB

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