AppContainer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. const { localStorage } = window;
  25. this.state = {
  26. editorMode: null,
  27. isDeviceSmallerThanMd: null,
  28. preferDarkModeByMediaQuery: false,
  29. preferDarkModeByUser: localStorage.preferDarkModeByUser === 'true',
  30. preferDrawerModeByUser: localStorage.preferDrawerModeByUser === 'true',
  31. preferDrawerModeOnEditByUser: // default: true
  32. localStorage.preferDrawerModeOnEditByUser == null || localStorage.preferDrawerModeOnEditByUser === 'true',
  33. isDrawerMode: null,
  34. isDrawerOpened: false,
  35. isPageCreateModalShown: false,
  36. recentlyUpdatedPages: [],
  37. };
  38. const body = document.querySelector('body');
  39. this.isAdmin = body.dataset.isAdmin === 'true';
  40. this.csrfToken = body.dataset.csrftoken;
  41. this.isPluginEnabled = body.dataset.pluginEnabled === 'true';
  42. this.isLoggedin = document.querySelector('body.nologin') == null;
  43. this.config = JSON.parse(document.getElementById('growi-context-hydrate').textContent || '{}');
  44. const currentUserElem = document.getElementById('growi-current-user');
  45. if (currentUserElem != null) {
  46. this.currentUser = JSON.parse(currentUserElem.textContent);
  47. }
  48. const userAgent = window.navigator.userAgent.toLowerCase();
  49. this.isMobile = /iphone|ipad|android/.test(userAgent);
  50. this.isDocSaved = true;
  51. this.originRenderer = new GrowiRenderer(this);
  52. this.interceptorManager = new InterceptorManager();
  53. this.interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(this), 10); // process as soon as possible
  54. this.interceptorManager.addInterceptor(new DrawioInterceptor(this), 20);
  55. this.interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(this), 900); // process as late as possible
  56. const userlang = body.dataset.userlang;
  57. this.i18n = i18nFactory(userlang);
  58. if (this.isLoggedin) {
  59. // remove old user cache
  60. this.removeOldUserCache();
  61. }
  62. this.containerInstances = {};
  63. this.componentInstances = {};
  64. this.rendererInstances = {};
  65. this.removeOldUserCache = this.removeOldUserCache.bind(this);
  66. this.apiGet = this.apiGet.bind(this);
  67. this.apiPost = this.apiPost.bind(this);
  68. this.apiDelete = this.apiDelete.bind(this);
  69. this.apiRequest = this.apiRequest.bind(this);
  70. this.apiv3Root = '/_api/v3';
  71. this.apiv3 = {
  72. get: this.apiv3Get.bind(this),
  73. post: this.apiv3Post.bind(this),
  74. put: this.apiv3Put.bind(this),
  75. delete: this.apiv3Delete.bind(this),
  76. };
  77. this.openPageCreateModal = this.openPageCreateModal.bind(this);
  78. this.closePageCreateModal = this.closePageCreateModal.bind(this);
  79. window.addEventListener('keydown', (event) => {
  80. const target = event.target;
  81. // ignore when target dom is input
  82. const inputPattern = /^input|textinput|textarea$/i;
  83. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  84. return;
  85. }
  86. if (event.key === 'c') {
  87. // don't fire when not needed
  88. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  89. this.setState({ isPageCreateModalShown: true });
  90. }
  91. }
  92. });
  93. }
  94. /**
  95. * Workaround for the mangling in production build to break constructor.name
  96. */
  97. static getClassName() {
  98. return 'AppContainer';
  99. }
  100. init() {
  101. this.initDeviceSize();
  102. this.initColorScheme();
  103. this.initPlugins();
  104. }
  105. initDeviceSize() {
  106. const mdOrAvobeHandler = async(mql) => {
  107. let isDeviceSmallerThanMd;
  108. // sm -> md
  109. if (mql.matches) {
  110. isDeviceSmallerThanMd = false;
  111. }
  112. // md -> sm
  113. else {
  114. isDeviceSmallerThanMd = true;
  115. }
  116. this.setState({ isDeviceSmallerThanMd });
  117. this.updateDrawerMode({ ...this.state, isDeviceSmallerThanMd }); // generate newest state object
  118. };
  119. this.addBreakpointListener('md', mdOrAvobeHandler, true);
  120. }
  121. async initColorScheme() {
  122. const switchStateByMediaQuery = async(mql) => {
  123. const preferDarkMode = mql.matches;
  124. await this.setState({ preferDarkModeByMediaQuery: preferDarkMode });
  125. this.applyColorScheme();
  126. };
  127. const mqlForDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
  128. // add event listener
  129. mqlForDarkMode.addListener(switchStateByMediaQuery);
  130. // initialize: check media query
  131. switchStateByMediaQuery(mqlForDarkMode);
  132. }
  133. initPlugins() {
  134. if (this.isPluginEnabled) {
  135. const growiPlugin = window.growiPlugin;
  136. growiPlugin.installAll(this, this.originRenderer);
  137. }
  138. }
  139. injectToWindow() {
  140. window.appContainer = this;
  141. const originRenderer = this.getOriginRenderer();
  142. window.growiRenderer = originRenderer;
  143. // backward compatibility
  144. window.crowi = this;
  145. window.crowiRenderer = originRenderer;
  146. window.crowiPlugin = window.growiPlugin;
  147. }
  148. get currentUserId() {
  149. if (this.currentUser == null) {
  150. return null;
  151. }
  152. return this.currentUser._id;
  153. }
  154. get currentUsername() {
  155. if (this.currentUser == null) {
  156. return null;
  157. }
  158. return this.currentUser.username;
  159. }
  160. /**
  161. * @return {Object} window.Crowi (js/legacy/crowi.js)
  162. */
  163. getCrowiForJquery() {
  164. return window.Crowi;
  165. }
  166. getConfig() {
  167. return this.config;
  168. }
  169. /**
  170. * Register unstated container instance
  171. * @param {object} instance unstated container instance
  172. */
  173. registerContainer(instance) {
  174. if (instance == null) {
  175. throw new Error('The specified instance must not be null');
  176. }
  177. const className = instance.constructor.getClassName();
  178. if (this.containerInstances[className] != null) {
  179. throw new Error('The specified instance couldn\'t register because the same type object has already been registered');
  180. }
  181. this.containerInstances[className] = instance;
  182. }
  183. /**
  184. * Get registered unstated container instance
  185. * !! THIS METHOD SHOULD ONLY BE USED FROM unstated CONTAINERS !!
  186. * !! From component instances, inject containers with `import { Subscribe } from 'unstated'` !!
  187. *
  188. * @param {string} className
  189. */
  190. getContainer(className) {
  191. return this.containerInstances[className];
  192. }
  193. /**
  194. * Register React component instance
  195. * @param {string} id
  196. * @param {object} instance React component instance
  197. */
  198. registerComponentInstance(id, instance) {
  199. if (instance == null) {
  200. throw new Error('The specified instance must not be null');
  201. }
  202. if (this.componentInstances[id] != null) {
  203. throw new Error('The specified instance couldn\'t register because the same id has already been registered');
  204. }
  205. this.componentInstances[id] = instance;
  206. }
  207. /**
  208. * Get registered React component instance
  209. * @param {string} id
  210. */
  211. getComponentInstance(id) {
  212. return this.componentInstances[id];
  213. }
  214. /**
  215. *
  216. * @param {string} breakpoint id of breakpoint
  217. * @param {function} handler event handler for media query
  218. * @param {boolean} invokeOnInit invoke handler after the initialization if true
  219. */
  220. addBreakpointListener(breakpoint, handler, invokeOnInit = false) {
  221. document.addEventListener('DOMContentLoaded', () => {
  222. // get the value of '--breakpoint-*'
  223. const breakpointPixel = parseInt(window.getComputedStyle(document.documentElement).getPropertyValue(`--breakpoint-${breakpoint}`), 10);
  224. const mediaQuery = window.matchMedia(`(min-width: ${breakpointPixel}px)`);
  225. // add event listener
  226. mediaQuery.addListener(handler);
  227. // initialize
  228. if (invokeOnInit) {
  229. handler(mediaQuery);
  230. }
  231. });
  232. }
  233. getOriginRenderer() {
  234. return this.originRenderer;
  235. }
  236. /**
  237. * factory method
  238. */
  239. getRenderer(mode) {
  240. if (this.rendererInstances[mode] != null) {
  241. return this.rendererInstances[mode];
  242. }
  243. const renderer = new GrowiRenderer(this, this.originRenderer);
  244. // setup
  245. renderer.initMarkdownItConfigurers(mode);
  246. renderer.setup(mode);
  247. // register
  248. this.rendererInstances[mode] = renderer;
  249. return renderer;
  250. }
  251. getEmojiStrategy() {
  252. return emojiStrategy;
  253. }
  254. removeOldUserCache() {
  255. if (window.localStorage.userByName == null) {
  256. return;
  257. }
  258. const keys = ['userByName', 'userById', 'users', 'lastFetched'];
  259. keys.forEach((key) => {
  260. window.localStorage.removeItem(key);
  261. });
  262. }
  263. async retrieveRecentlyUpdated() {
  264. const { data } = await this.apiv3Get('/pages/recent');
  265. this.setState({ recentlyUpdatedPages: data.pages });
  266. }
  267. setEditorMode(editorMode) {
  268. this.setState({ editorMode });
  269. this.updateDrawerMode({ ...this.state, editorMode }); // generate newest state object
  270. }
  271. toggleDrawer() {
  272. const { isDrawerOpened } = this.state;
  273. this.setState({ isDrawerOpened: !isDrawerOpened });
  274. }
  275. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  276. let targetComponent;
  277. switch (componentKind) {
  278. case 'page':
  279. targetComponent = this.getComponentInstance('Page');
  280. break;
  281. }
  282. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  283. }
  284. launchDrawioModal(componentKind, beginLineNumber, endLineNumber) {
  285. let targetComponent;
  286. switch (componentKind) {
  287. case 'page':
  288. targetComponent = this.getComponentInstance('Page');
  289. break;
  290. }
  291. targetComponent.launchDrawioModal(beginLineNumber, endLineNumber);
  292. }
  293. /**
  294. * Set Sidebar mode preference by user
  295. * @param {boolean} preferDockMode
  296. */
  297. async setDrawerModePreference(bool) {
  298. this.setState({ preferDrawerModeByUser: bool });
  299. this.updateDrawerMode({ ...this.state, preferDrawerModeByUser: bool }); // generate newest state object
  300. // store settings to localStorage
  301. const { localStorage } = window;
  302. localStorage.preferDrawerModeByUser = bool;
  303. }
  304. /**
  305. * Set Sidebar mode preference by user
  306. * @param {boolean} preferDockMode
  307. */
  308. async setDrawerModePreferenceOnEdit(bool) {
  309. this.setState({ preferDrawerModeOnEditByUser: bool });
  310. this.updateDrawerMode({ ...this.state, preferDrawerModeOnEditByUser: bool }); // generate newest state object
  311. // store settings to localStorage
  312. const { localStorage } = window;
  313. localStorage.preferDrawerModeOnEditByUser = bool;
  314. }
  315. /**
  316. * Update drawer related state by specified 'newState' object
  317. * @param {object} newState A newest state object
  318. *
  319. * Specify 'newState' like following code:
  320. *
  321. * { ...this.state, overwriteParam: overwriteValue }
  322. *
  323. * because updating state of unstated container will be delayed unless you use await
  324. */
  325. updateDrawerMode(newState) {
  326. const {
  327. editorMode, isDeviceSmallerThanMd, preferDrawerModeByUser, preferDrawerModeOnEditByUser,
  328. } = newState;
  329. // get preference on view or edit
  330. const preferDrawerMode = editorMode != null ? preferDrawerModeOnEditByUser : preferDrawerModeByUser;
  331. const isDrawerMode = isDeviceSmallerThanMd || preferDrawerMode;
  332. const isDrawerOpened = false; // close Drawer anyway
  333. this.setState({ isDrawerMode, isDrawerOpened });
  334. }
  335. /**
  336. * Set color scheme preference by user
  337. * @param {boolean} isDarkMode
  338. */
  339. async setColorSchemePreference(isDarkMode) {
  340. await this.setState({ preferDarkModeByUser: isDarkMode });
  341. // store settings to localStorage
  342. const { localStorage } = window;
  343. if (isDarkMode == null) {
  344. delete localStorage.removeItem('preferDarkModeByUser');
  345. }
  346. else {
  347. localStorage.preferDarkModeByUser = isDarkMode;
  348. }
  349. this.applyColorScheme();
  350. }
  351. /**
  352. * Apply color scheme as 'dark' attribute of <html></html>
  353. */
  354. applyColorScheme() {
  355. const { preferDarkModeByMediaQuery, preferDarkModeByUser } = this.state;
  356. let isDarkMode = preferDarkModeByMediaQuery;
  357. if (preferDarkModeByUser != null) {
  358. isDarkMode = preferDarkModeByUser;
  359. }
  360. // switch to dark mode
  361. if (isDarkMode) {
  362. document.documentElement.removeAttribute('light');
  363. document.documentElement.setAttribute('dark', 'true');
  364. }
  365. // switch to light mode
  366. else {
  367. document.documentElement.setAttribute('light', 'true');
  368. document.documentElement.removeAttribute('dark');
  369. }
  370. }
  371. async apiGet(path, params) {
  372. return this.apiRequest('get', path, { params });
  373. }
  374. async apiPost(path, params) {
  375. if (!params._csrf) {
  376. params._csrf = this.csrfToken;
  377. }
  378. return this.apiRequest('post', path, params);
  379. }
  380. async apiDelete(path, params) {
  381. if (!params._csrf) {
  382. params._csrf = this.csrfToken;
  383. }
  384. return this.apiRequest('delete', path, { data: params });
  385. }
  386. async apiRequest(method, path, params) {
  387. const res = await axios[method](`/_api${path}`, params);
  388. if (res.data.ok) {
  389. return res.data;
  390. }
  391. // Return error code if code is exist
  392. if (res.data.code != null) {
  393. const error = new Apiv1ErrorHandler(res.data.error, res.data.code);
  394. throw error;
  395. }
  396. throw new Error(res.data.error);
  397. }
  398. async apiv3Request(method, path, params) {
  399. try {
  400. const res = await axios[method](urljoin(this.apiv3Root, path), params);
  401. return res.data;
  402. }
  403. catch (err) {
  404. const errors = apiv3ErrorHandler(err);
  405. throw errors;
  406. }
  407. }
  408. async apiv3Get(path, params) {
  409. return this.apiv3Request('get', path, { params });
  410. }
  411. async apiv3Post(path, params = {}) {
  412. if (!params._csrf) {
  413. params._csrf = this.csrfToken;
  414. }
  415. return this.apiv3Request('post', path, params);
  416. }
  417. async apiv3Put(path, params = {}) {
  418. if (!params._csrf) {
  419. params._csrf = this.csrfToken;
  420. }
  421. return this.apiv3Request('put', path, params);
  422. }
  423. async apiv3Delete(path, params = {}) {
  424. if (!params._csrf) {
  425. params._csrf = this.csrfToken;
  426. }
  427. return this.apiv3Request('delete', path, { params });
  428. }
  429. openPageCreateModal() {
  430. this.setState({ isPageCreateModalShown: true });
  431. }
  432. closePageCreateModal() {
  433. this.setState({ isPageCreateModalShown: false });
  434. }
  435. }