AppContainer.js 12 KB

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