AppContainer.js 11 KB

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