AppContainer.js 12 KB

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