AppContainer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. this.users = [];
  54. this.userByName = {};
  55. this.userById = {};
  56. this.recoverData();
  57. if (this.isLoggedin) {
  58. this.fetchUsers();
  59. }
  60. this.containerInstances = {};
  61. this.componentInstances = {};
  62. this.rendererInstances = {};
  63. this.fetchUsers = this.fetchUsers.bind(this);
  64. this.apiGet = this.apiGet.bind(this);
  65. this.apiPost = this.apiPost.bind(this);
  66. this.apiDelete = this.apiDelete.bind(this);
  67. this.apiRequest = this.apiRequest.bind(this);
  68. this.apiv3Root = '/_api/v3';
  69. this.apiv3 = {
  70. get: this.apiv3Get.bind(this),
  71. post: this.apiv3Post.bind(this),
  72. put: this.apiv3Put.bind(this),
  73. delete: this.apiv3Delete.bind(this),
  74. };
  75. this.openPageCreateModal = this.openPageCreateModal.bind(this);
  76. this.closePageCreateModal = this.closePageCreateModal.bind(this);
  77. }
  78. /**
  79. * Workaround for the mangling in production build to break constructor.name
  80. */
  81. static getClassName() {
  82. return 'AppContainer';
  83. }
  84. init() {
  85. this.initColorScheme();
  86. this.initPlugins();
  87. }
  88. async initColorScheme() {
  89. const switchStateByMediaQuery = (mql) => {
  90. const preferDarkMode = mql.matches;
  91. this.setState({ preferDarkModeByMediaQuery: preferDarkMode });
  92. this.applyColorScheme();
  93. };
  94. const mqlForDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
  95. // add event listener
  96. mqlForDarkMode.addListener(switchStateByMediaQuery);
  97. // restore settings from localStorage
  98. const { localStorage } = window;
  99. if (localStorage.preferDarkModeByUser != null) {
  100. await this.setState({ preferDarkModeByUser: localStorage.preferDarkModeByUser === 'true' });
  101. }
  102. // initialize
  103. switchStateByMediaQuery(mqlForDarkMode);
  104. }
  105. initPlugins() {
  106. if (this.isPluginEnabled) {
  107. const growiPlugin = window.growiPlugin;
  108. growiPlugin.installAll(this, this.originRenderer);
  109. }
  110. }
  111. injectToWindow() {
  112. window.appContainer = this;
  113. const originRenderer = this.getOriginRenderer();
  114. window.growiRenderer = originRenderer;
  115. // backward compatibility
  116. window.crowi = this;
  117. window.crowiRenderer = originRenderer;
  118. window.crowiPlugin = window.growiPlugin;
  119. }
  120. get currentUserId() {
  121. if (this.currentUser == null) {
  122. return null;
  123. }
  124. return this.currentUser._id;
  125. }
  126. get currentUsername() {
  127. if (this.currentUser == null) {
  128. return null;
  129. }
  130. return this.currentUser.username;
  131. }
  132. /**
  133. * @return {Object} window.Crowi (js/legacy/crowi.js)
  134. */
  135. getCrowiForJquery() {
  136. return window.Crowi;
  137. }
  138. getConfig() {
  139. return this.config;
  140. }
  141. /**
  142. * Register unstated container instance
  143. * @param {object} instance unstated container instance
  144. */
  145. registerContainer(instance) {
  146. if (instance == null) {
  147. throw new Error('The specified instance must not be null');
  148. }
  149. const className = instance.constructor.getClassName();
  150. if (this.containerInstances[className] != null) {
  151. throw new Error('The specified instance couldn\'t register because the same type object has already been registered');
  152. }
  153. this.containerInstances[className] = instance;
  154. }
  155. /**
  156. * Get registered unstated container instance
  157. * !! THIS METHOD SHOULD ONLY BE USED FROM unstated CONTAINERS !!
  158. * !! From component instances, inject containers with `import { Subscribe } from 'unstated'` !!
  159. *
  160. * @param {string} className
  161. */
  162. getContainer(className) {
  163. return this.containerInstances[className];
  164. }
  165. /**
  166. * Register React component instance
  167. * @param {string} id
  168. * @param {object} instance React component instance
  169. */
  170. registerComponentInstance(id, instance) {
  171. if (instance == null) {
  172. throw new Error('The specified instance must not be null');
  173. }
  174. if (this.componentInstances[id] != null) {
  175. throw new Error('The specified instance couldn\'t register because the same id has already been registered');
  176. }
  177. this.componentInstances[id] = instance;
  178. }
  179. /**
  180. * Get registered React component instance
  181. * @param {string} id
  182. */
  183. getComponentInstance(id) {
  184. return this.componentInstances[id];
  185. }
  186. /**
  187. *
  188. * @param {string} breakpoint id of breakpoint
  189. * @param {function} handler event handler for media query
  190. * @param {boolean} invokeOnInit invoke handler after the initialization if true
  191. */
  192. addBreakpointListener(breakpoint, handler, invokeOnInit = false) {
  193. document.addEventListener('DOMContentLoaded', () => {
  194. // get the value of '--breakpoint-*'
  195. const breakpointPixel = parseInt(window.getComputedStyle(document.documentElement).getPropertyValue(`--breakpoint-${breakpoint}`), 10);
  196. const mediaQuery = window.matchMedia(`(min-width: ${breakpointPixel}px)`);
  197. // add event listener
  198. mediaQuery.addListener(handler);
  199. // initialize
  200. if (invokeOnInit) {
  201. handler(mediaQuery);
  202. }
  203. });
  204. }
  205. getOriginRenderer() {
  206. return this.originRenderer;
  207. }
  208. /**
  209. * factory method
  210. */
  211. getRenderer(mode) {
  212. if (this.rendererInstances[mode] != null) {
  213. return this.rendererInstances[mode];
  214. }
  215. const renderer = new GrowiRenderer(this, this.originRenderer);
  216. // setup
  217. renderer.initMarkdownItConfigurers(mode);
  218. renderer.setup(mode);
  219. // register
  220. this.rendererInstances[mode] = renderer;
  221. return renderer;
  222. }
  223. getEmojiStrategy() {
  224. return emojiStrategy;
  225. }
  226. recoverData() {
  227. const keys = [
  228. 'userByName',
  229. 'userById',
  230. 'users',
  231. ];
  232. keys.forEach((key) => {
  233. const keyContent = window.localStorage[key];
  234. if (keyContent) {
  235. try {
  236. this[key] = JSON.parse(keyContent);
  237. }
  238. catch (e) {
  239. window.localStorage.removeItem(key);
  240. }
  241. }
  242. });
  243. }
  244. async retrieveRecentlyUpdated() {
  245. const { data } = await this.apiv3Get('/pages/recent');
  246. this.setState({ recentlyUpdatedPages: data.pages });
  247. }
  248. fetchUsers() {
  249. const interval = 1000 * 60 * 15; // 15min
  250. const currentTime = new Date();
  251. if (window.localStorage.lastFetched && interval > currentTime - new Date(window.localStorage.lastFetched)) {
  252. return;
  253. }
  254. this.apiGet('/users.list', {})
  255. .then((data) => {
  256. this.users = data.users;
  257. window.localStorage.users = JSON.stringify(data.users);
  258. const userByName = {};
  259. const userById = {};
  260. for (let i = 0; i < data.users.length; i++) {
  261. const user = data.users[i];
  262. userByName[user.username] = user;
  263. userById[user._id] = user;
  264. }
  265. this.userByName = userByName;
  266. window.localStorage.userByName = JSON.stringify(userByName);
  267. this.userById = userById;
  268. window.localStorage.userById = JSON.stringify(userById);
  269. window.localStorage.lastFetched = new Date();
  270. })
  271. .catch((err) => {
  272. window.localStorage.removeItem('lastFetched');
  273. // ignore errors
  274. });
  275. }
  276. findUserById(userId) {
  277. if (this.userById && this.userById[userId]) {
  278. return this.userById[userId];
  279. }
  280. return null;
  281. }
  282. findUserByIds(userIds) {
  283. const users = [];
  284. for (const userId of userIds) {
  285. const user = this.findUserById(userId);
  286. if (user) {
  287. users.push(user);
  288. }
  289. }
  290. return users;
  291. }
  292. toggleDrawer() {
  293. const { isDrawerOpened } = this.state;
  294. this.setState({ isDrawerOpened: !isDrawerOpened });
  295. }
  296. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  297. let targetComponent;
  298. switch (componentKind) {
  299. case 'page':
  300. targetComponent = this.getComponentInstance('Page');
  301. break;
  302. }
  303. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  304. }
  305. launchDrawioModal(componentKind, beginLineNumber, endLineNumber) {
  306. let targetComponent;
  307. switch (componentKind) {
  308. case 'page':
  309. targetComponent = this.getComponentInstance('Page');
  310. break;
  311. }
  312. targetComponent.launchDrawioModal(beginLineNumber, endLineNumber);
  313. }
  314. /**
  315. * Set color scheme preference by user
  316. * @param {boolean} isDarkMode
  317. */
  318. async setColorSchemePreference(isDarkMode) {
  319. await this.setState({ preferDarkModeByUser: isDarkMode });
  320. // store settings to localStorage
  321. const { localStorage } = window;
  322. if (isDarkMode == null) {
  323. delete localStorage.removeItem('preferDarkModeByUser');
  324. }
  325. else {
  326. localStorage.preferDarkModeByUser = isDarkMode;
  327. }
  328. this.applyColorScheme();
  329. }
  330. /**
  331. * Apply color scheme as 'dark' attribute of <html></html>
  332. */
  333. applyColorScheme() {
  334. const { preferDarkModeByMediaQuery, preferDarkModeByUser } = this.state;
  335. let isDarkMode = preferDarkModeByMediaQuery;
  336. if (preferDarkModeByUser != null) {
  337. isDarkMode = preferDarkModeByUser;
  338. }
  339. // switch to dark mode
  340. if (isDarkMode) {
  341. document.documentElement.removeAttribute('light');
  342. document.documentElement.setAttribute('dark', 'true');
  343. }
  344. // switch to light mode
  345. else {
  346. document.documentElement.setAttribute('light', 'true');
  347. document.documentElement.removeAttribute('dark');
  348. }
  349. }
  350. async apiGet(path, params) {
  351. return this.apiRequest('get', path, { params });
  352. }
  353. async apiPost(path, params) {
  354. if (!params._csrf) {
  355. params._csrf = this.csrfToken;
  356. }
  357. return this.apiRequest('post', path, params);
  358. }
  359. async apiDelete(path, params) {
  360. if (!params._csrf) {
  361. params._csrf = this.csrfToken;
  362. }
  363. return this.apiRequest('delete', path, { data: params });
  364. }
  365. async apiRequest(method, path, params) {
  366. const res = await axios[method](`/_api${path}`, params);
  367. if (res.data.ok) {
  368. return res.data;
  369. }
  370. // Return error code if code is exist
  371. if (res.data.code != null) {
  372. const error = new Apiv1ErrorHandler(res.data.error, res.data.code);
  373. throw error;
  374. }
  375. throw new Error(res.data.error);
  376. }
  377. async apiv3Request(method, path, params) {
  378. try {
  379. const res = await axios[method](urljoin(this.apiv3Root, path), params);
  380. return res.data;
  381. }
  382. catch (err) {
  383. const errors = apiv3ErrorHandler(err);
  384. throw errors;
  385. }
  386. }
  387. async apiv3Get(path, params) {
  388. return this.apiv3Request('get', path, { params });
  389. }
  390. async apiv3Post(path, params = {}) {
  391. if (!params._csrf) {
  392. params._csrf = this.csrfToken;
  393. }
  394. return this.apiv3Request('post', path, params);
  395. }
  396. async apiv3Put(path, params = {}) {
  397. if (!params._csrf) {
  398. params._csrf = this.csrfToken;
  399. }
  400. return this.apiv3Request('put', path, params);
  401. }
  402. async apiv3Delete(path, params = {}) {
  403. if (!params._csrf) {
  404. params._csrf = this.csrfToken;
  405. }
  406. return this.apiv3Request('delete', path, { params });
  407. }
  408. openPageCreateModal() {
  409. this.setState({ isPageCreateModalShown: true });
  410. }
  411. closePageCreateModal() {
  412. this.setState({ isPageCreateModalShown: false });
  413. }
  414. }