AppContainer.js 12 KB

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