AppContainer.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. mediaQueryListForDarkMode,
  9. applyColorScheme,
  10. } from '../util/color-scheme';
  11. import Apiv1ErrorHandler from '../util/apiv1ErrorHandler';
  12. import { i18nFactory } from '../util/i18n';
  13. import apiv3ErrorHandler from '../util/apiv3ErrorHandler';
  14. /**
  15. * Service container related to options for Application
  16. * @extends {Container} unstated Container
  17. */
  18. export default class AppContainer extends Container {
  19. constructor() {
  20. super();
  21. this.state = {
  22. preferDarkModeByMediaQuery: false,
  23. // stetes for contents
  24. recentlyUpdatedPages: [],
  25. };
  26. const body = document.querySelector('body');
  27. this.csrfToken = body.dataset.csrftoken;
  28. this.config = JSON.parse(document.getElementById('growi-context-hydrate').textContent || '{}');
  29. const userAgent = window.navigator.userAgent.toLowerCase();
  30. this.isMobile = /iphone|ipad|android/.test(userAgent);
  31. const currentUserElem = document.getElementById('growi-current-user');
  32. if (currentUserElem != null) {
  33. this.currentUser = JSON.parse(currentUserElem.textContent);
  34. }
  35. const isSharedPageElem = document.getElementById('is-shared-page');
  36. // check what kind of user
  37. this.isGuestUser = this.currentUser == null;
  38. this.isSharedUser = isSharedPageElem != null && this.currentUser == null;
  39. // TAICHI: check if Link Sharing is enabled or not
  40. // this.isLinkSharingForbidden =
  41. const userLocaleId = this.currentUser?.lang;
  42. this.i18n = i18nFactory(userLocaleId);
  43. this.containerInstances = {};
  44. this.componentInstances = {};
  45. this.rendererInstances = {};
  46. this.apiGet = this.apiGet.bind(this);
  47. this.apiPost = this.apiPost.bind(this);
  48. this.apiDelete = this.apiDelete.bind(this);
  49. this.apiRequest = this.apiRequest.bind(this);
  50. this.apiv3Root = '/_api/v3';
  51. this.apiv3 = {
  52. get: this.apiv3Get.bind(this),
  53. post: this.apiv3Post.bind(this),
  54. put: this.apiv3Put.bind(this),
  55. delete: this.apiv3Delete.bind(this),
  56. };
  57. }
  58. /**
  59. * Workaround for the mangling in production build to break constructor.name
  60. */
  61. static getClassName() {
  62. return 'AppContainer';
  63. }
  64. initApp() {
  65. this.initMediaQueryForColorScheme();
  66. this.injectToWindow();
  67. }
  68. initContents() {
  69. const body = document.querySelector('body');
  70. this.isAdmin = body.dataset.isAdmin === 'true';
  71. this.isDocSaved = true;
  72. this.originRenderer = new GrowiRenderer(this);
  73. this.interceptorManager = new InterceptorManager();
  74. if (this.currentUser != null) {
  75. // remove old user cache
  76. this.removeOldUserCache();
  77. }
  78. const isPluginEnabled = body.dataset.pluginEnabled === 'true';
  79. if (isPluginEnabled) {
  80. this.initPlugins();
  81. }
  82. this.injectToWindow();
  83. }
  84. async initMediaQueryForColorScheme() {
  85. const switchStateByMediaQuery = async(mql) => {
  86. const preferDarkMode = mql.matches;
  87. this.setState({ preferDarkModeByMediaQuery: preferDarkMode });
  88. applyColorScheme();
  89. };
  90. // add event listener
  91. mediaQueryListForDarkMode.addListener(switchStateByMediaQuery);
  92. }
  93. initPlugins() {
  94. const growiPlugin = window.growiPlugin;
  95. growiPlugin.installAll(this, this.originRenderer);
  96. }
  97. injectToWindow() {
  98. window.appContainer = this;
  99. const originRenderer = this.getOriginRenderer();
  100. window.growiRenderer = originRenderer;
  101. // backward compatibility
  102. window.crowi = this;
  103. window.crowiRenderer = originRenderer;
  104. window.crowiPlugin = window.growiPlugin;
  105. }
  106. get currentUserId() {
  107. if (this.currentUser == null) {
  108. return null;
  109. }
  110. return this.currentUser._id;
  111. }
  112. get currentUsername() {
  113. if (this.currentUser == null) {
  114. return null;
  115. }
  116. return this.currentUser.username;
  117. }
  118. /**
  119. * @return {Object} window.Crowi (js/legacy/crowi.js)
  120. */
  121. getCrowiForJquery() {
  122. return window.Crowi;
  123. }
  124. getConfig() {
  125. return this.config;
  126. }
  127. /**
  128. * Register unstated container instance
  129. * @param {object} instance unstated container instance
  130. */
  131. registerContainer(instance) {
  132. if (instance == null) {
  133. throw new Error('The specified instance must not be null');
  134. }
  135. const className = instance.constructor.getClassName();
  136. if (this.containerInstances[className] != null) {
  137. throw new Error('The specified instance couldn\'t register because the same type object has already been registered');
  138. }
  139. this.containerInstances[className] = instance;
  140. }
  141. /**
  142. * Get registered unstated container instance
  143. * !! THIS METHOD SHOULD ONLY BE USED FROM unstated CONTAINERS !!
  144. * !! From component instances, inject containers with `import { Subscribe } from 'unstated'` !!
  145. *
  146. * @param {string} className
  147. */
  148. getContainer(className) {
  149. return this.containerInstances[className];
  150. }
  151. /**
  152. * Register React component instance
  153. * @param {string} id
  154. * @param {object} instance React component instance
  155. */
  156. registerComponentInstance(id, instance) {
  157. if (instance == null) {
  158. throw new Error('The specified instance must not be null');
  159. }
  160. if (this.componentInstances[id] != null) {
  161. throw new Error('The specified instance couldn\'t register because the same id has already been registered');
  162. }
  163. this.componentInstances[id] = instance;
  164. }
  165. /**
  166. * Get registered React component instance
  167. * @param {string} id
  168. */
  169. getComponentInstance(id) {
  170. return this.componentInstances[id];
  171. }
  172. /**
  173. *
  174. * @param {string} breakpoint id of breakpoint
  175. * @param {function} handler event handler for media query
  176. * @param {boolean} invokeOnInit invoke handler after the initialization if true
  177. */
  178. addBreakpointListener(breakpoint, handler, invokeOnInit = false) {
  179. document.addEventListener('DOMContentLoaded', () => {
  180. // get the value of '--breakpoint-*'
  181. const breakpointPixel = parseInt(window.getComputedStyle(document.documentElement).getPropertyValue(`--breakpoint-${breakpoint}`), 10);
  182. const mediaQuery = window.matchMedia(`(min-width: ${breakpointPixel}px)`);
  183. // add event listener
  184. mediaQuery.addListener(handler);
  185. // initialize
  186. if (invokeOnInit) {
  187. handler(mediaQuery);
  188. }
  189. });
  190. }
  191. getOriginRenderer() {
  192. return this.originRenderer;
  193. }
  194. /**
  195. * factory method
  196. */
  197. getRenderer(mode) {
  198. if (this.rendererInstances[mode] != null) {
  199. return this.rendererInstances[mode];
  200. }
  201. const renderer = new GrowiRenderer(this, this.originRenderer);
  202. // setup
  203. renderer.initMarkdownItConfigurers(mode);
  204. renderer.setup(mode);
  205. // register
  206. this.rendererInstances[mode] = renderer;
  207. return renderer;
  208. }
  209. getEmojiStrategy() {
  210. return emojiStrategy;
  211. }
  212. removeOldUserCache() {
  213. if (window.localStorage.userByName == null) {
  214. return;
  215. }
  216. const keys = ['userByName', 'userById', 'users', 'lastFetched'];
  217. keys.forEach((key) => {
  218. window.localStorage.removeItem(key);
  219. });
  220. }
  221. async retrieveRecentlyUpdated() {
  222. const { data } = await this.apiv3Get('/pages/recent');
  223. this.setState({ recentlyUpdatedPages: data.pages });
  224. }
  225. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  226. let targetComponent;
  227. switch (componentKind) {
  228. case 'page':
  229. targetComponent = this.getComponentInstance('Page');
  230. break;
  231. }
  232. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  233. }
  234. launchDrawioModal(componentKind, beginLineNumber, endLineNumber) {
  235. let targetComponent;
  236. switch (componentKind) {
  237. case 'page':
  238. targetComponent = this.getComponentInstance('Page');
  239. break;
  240. }
  241. targetComponent.launchDrawioModal(beginLineNumber, endLineNumber);
  242. }
  243. async apiGet(path, params) {
  244. return this.apiRequest('get', path, { params });
  245. }
  246. async apiPost(path, params) {
  247. if (!params._csrf) {
  248. params._csrf = this.csrfToken;
  249. }
  250. return this.apiRequest('post', path, params);
  251. }
  252. async apiDelete(path, params) {
  253. if (!params._csrf) {
  254. params._csrf = this.csrfToken;
  255. }
  256. return this.apiRequest('delete', path, { data: params });
  257. }
  258. async apiRequest(method, path, params) {
  259. const res = await axios[method](`/_api${path}`, params);
  260. if (res.data.ok) {
  261. return res.data;
  262. }
  263. // Return error code if code is exist
  264. if (res.data.code != null) {
  265. const error = new Apiv1ErrorHandler(res.data.error, res.data.code);
  266. throw error;
  267. }
  268. throw new Error(res.data.error);
  269. }
  270. async apiv3Request(method, path, params) {
  271. try {
  272. const res = await axios[method](urljoin(this.apiv3Root, path), params);
  273. return res.data;
  274. }
  275. catch (err) {
  276. const errors = apiv3ErrorHandler(err);
  277. throw errors;
  278. }
  279. }
  280. async apiv3Get(path, params) {
  281. return this.apiv3Request('get', path, { params });
  282. }
  283. async apiv3Post(path, params = {}) {
  284. if (!params._csrf) {
  285. params._csrf = this.csrfToken;
  286. }
  287. return this.apiv3Request('post', path, params);
  288. }
  289. async apiv3Put(path, params = {}) {
  290. if (!params._csrf) {
  291. params._csrf = this.csrfToken;
  292. }
  293. return this.apiv3Request('put', path, params);
  294. }
  295. async apiv3Delete(path, params = {}) {
  296. if (!params._csrf) {
  297. params._csrf = this.csrfToken;
  298. }
  299. return this.apiv3Request('delete', path, { params });
  300. }
  301. }