PageContainer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import { Container } from 'unstated';
  2. import loggerFactory from '@alias/logger';
  3. import * as entities from 'entities';
  4. import * as toastr from 'toastr';
  5. import { toastError } from '../util/apiNotification';
  6. import {
  7. DetachCodeBlockInterceptor,
  8. RestoreCodeBlockInterceptor,
  9. } from '../util/interceptor/detach-code-blocks';
  10. import {
  11. DrawioInterceptor,
  12. } from '../util/interceptor/drawio-interceptor';
  13. const logger = loggerFactory('growi:services:PageContainer');
  14. /**
  15. * Service container related to Page
  16. * @extends {Container} unstated Container
  17. */
  18. export default class PageContainer extends Container {
  19. constructor(appContainer) {
  20. super();
  21. this.appContainer = appContainer;
  22. this.appContainer.registerContainer(this);
  23. this.state = {};
  24. const mainContent = document.querySelector('#content-main');
  25. if (mainContent == null) {
  26. logger.debug('#content-main element is not exists');
  27. return;
  28. }
  29. const revisionId = mainContent.getAttribute('data-page-revision-id');
  30. const path = decodeURI(mainContent.getAttribute('data-path'));
  31. this.state = {
  32. // local page data
  33. markdown: null, // will be initialized after initStateMarkdown()
  34. pageId: mainContent.getAttribute('data-page-id'),
  35. revisionId,
  36. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  37. revisionAuthor: JSON.parse(mainContent.getAttribute('data-page-revision-author')),
  38. path,
  39. tocHtml: '',
  40. isLiked: JSON.parse(mainContent.getAttribute('data-page-is-liked')),
  41. seenUsers: [],
  42. likerUsers: [],
  43. sumOfSeenUsers: 0,
  44. sumOfLikers: 0,
  45. createdAt: mainContent.getAttribute('data-page-created-at'),
  46. creator: JSON.parse(mainContent.getAttribute('data-page-creator')),
  47. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  48. isForbidden: JSON.parse(mainContent.getAttribute('data-page-is-forbidden')),
  49. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  50. isDeletable: JSON.parse(mainContent.getAttribute('data-page-is-deletable')),
  51. isAbleToDeleteCompletely: JSON.parse(mainContent.getAttribute('data-page-is-able-to-delete-completely')),
  52. pageUser: JSON.parse(mainContent.getAttribute('data-page-user')),
  53. tags: null,
  54. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  55. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  56. // latest(on remote) information
  57. remoteRevisionId: revisionId,
  58. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  59. lastUpdateUsername: undefined,
  60. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  61. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  62. isHackmdDraftUpdatingInRealtime: false,
  63. };
  64. const { interceptorManager } = this.appContainer;
  65. interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(appContainer), 10); // process as soon as possible
  66. interceptorManager.addInterceptor(new DrawioInterceptor(appContainer), 20);
  67. interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(appContainer), 900); // process as late as possible
  68. this.initStateMarkdown();
  69. this.initStateOthers();
  70. this.setTocHtml = this.setTocHtml.bind(this);
  71. this.save = this.save.bind(this);
  72. this.checkAndUpdateImageUrlCached = this.checkAndUpdateImageUrlCached.bind(this);
  73. this.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  74. this.addWebSocketEventHandlers();
  75. const unlinkPageButton = document.getElementById('unlink-page-button');
  76. if (unlinkPageButton != null) {
  77. unlinkPageButton.addEventListener('click', async() => {
  78. try {
  79. const res = await this.appContainer.apiPost('/pages.unlink', { path });
  80. window.location.href = encodeURI(`${res.path}?unlinked=true`);
  81. }
  82. catch (err) {
  83. toastError(err);
  84. }
  85. });
  86. }
  87. }
  88. /**
  89. * Workaround for the mangling in production build to break constructor.name
  90. */
  91. static getClassName() {
  92. return 'PageContainer';
  93. }
  94. /**
  95. * initialize state for markdown data
  96. */
  97. initStateMarkdown() {
  98. let pageContent = '';
  99. const rawText = document.getElementById('raw-text-original');
  100. if (rawText) {
  101. pageContent = rawText.innerHTML;
  102. }
  103. const markdown = entities.decodeHTML(pageContent);
  104. this.state.markdown = markdown;
  105. }
  106. async initStateOthers() {
  107. const seenUserListElem = document.getElementById('seen-user-list');
  108. if (seenUserListElem != null) {
  109. const { userIdsStr, sumOfSeenUsers } = seenUserListElem.dataset;
  110. this.setState({ sumOfSeenUsers });
  111. if (userIdsStr === '') {
  112. return;
  113. }
  114. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: userIdsStr });
  115. this.setState({ seenUsers: users });
  116. this.checkAndUpdateImageUrlCached(users);
  117. }
  118. const likerListElem = document.getElementById('liker-list');
  119. if (likerListElem != null) {
  120. const { userIdsStr, sumOfLikers } = likerListElem.dataset;
  121. this.setState({ sumOfLikers });
  122. if (userIdsStr === '') {
  123. return;
  124. }
  125. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: userIdsStr });
  126. this.setState({ likerUsers: users });
  127. this.checkAndUpdateImageUrlCached(users);
  128. }
  129. }
  130. async checkAndUpdateImageUrlCached(users) {
  131. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  132. if (noImageCacheUsers.length === 0) {
  133. return;
  134. }
  135. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  136. try {
  137. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  138. }
  139. catch (err) {
  140. // Error alert doesn't apear, because user don't need to notice this error.
  141. logger.error(err);
  142. }
  143. }
  144. get navigationContainer() {
  145. return this.appContainer.getContainer('NavigationContainer');
  146. }
  147. setLatestRemotePageData(page, user) {
  148. this.setState({
  149. remoteRevisionId: page.revision._id,
  150. revisionIdHackmdSynced: page.revisionHackmdSynced,
  151. lastUpdateUsername: user.name,
  152. });
  153. }
  154. setTocHtml(tocHtml) {
  155. if (this.state.tocHtml !== tocHtml) {
  156. this.setState({ tocHtml });
  157. }
  158. }
  159. /**
  160. * save success handler
  161. * @param {object} page Page instance
  162. * @param {Array[Tag]} tags Array of Tag
  163. */
  164. updateStateAfterSave(page, tags) {
  165. const { editorMode } = this.navigationContainer.state;
  166. // update state of PageContainer
  167. const newState = {
  168. pageId: page._id,
  169. revisionId: page.revision._id,
  170. revisionCreatedAt: new Date(page.revision.createdAt).getTime() / 1000,
  171. remoteRevisionId: page.revision._id,
  172. revisionIdHackmdSynced: page.revisionHackmdSynced,
  173. hasDraftOnHackmd: page.hasDraftOnHackmd,
  174. markdown: page.revision.body,
  175. };
  176. if (tags != null) {
  177. newState.tags = tags;
  178. }
  179. this.setState(newState);
  180. // PageEditor component
  181. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  182. if (pageEditor != null) {
  183. if (editorMode !== 'builtin') {
  184. pageEditor.updateEditorValue(newState.markdown);
  185. }
  186. }
  187. // PageEditorByHackmd component
  188. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  189. if (pageEditorByHackmd != null) {
  190. // reset
  191. if (editorMode !== 'hackmd') {
  192. pageEditorByHackmd.reset();
  193. }
  194. }
  195. // hidden input
  196. $('input[name="revision_id"]').val(newState.revisionId);
  197. }
  198. /**
  199. * Save page
  200. * @param {string} markdown
  201. * @param {object} optionsToSave
  202. * @return {object} { page: Page, tags: Tag[] }
  203. */
  204. async save(markdown, optionsToSave = {}) {
  205. const { editorMode } = this.navigationContainer.state;
  206. const { pageId, path } = this.state;
  207. let { revisionId } = this.state;
  208. const options = Object.assign({}, optionsToSave);
  209. if (editorMode === 'hackmd') {
  210. // set option to sync
  211. options.isSyncRevisionToHackmd = true;
  212. revisionId = this.state.revisionIdHackmdSynced;
  213. }
  214. let res;
  215. if (pageId == null) {
  216. res = await this.createPage(path, markdown, options);
  217. }
  218. else {
  219. res = await this.updatePage(pageId, revisionId, markdown, options);
  220. }
  221. this.updateStateAfterSave(res.page, res.tags);
  222. return res;
  223. }
  224. async saveAndReload(optionsToSave) {
  225. if (optionsToSave == null) {
  226. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  227. throw new Error(msg);
  228. }
  229. const { editorMode } = this.navigationContainer.state;
  230. if (editorMode == null) {
  231. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  232. return;
  233. }
  234. const { pageId, path } = this.state;
  235. let { revisionId } = this.state;
  236. const options = Object.assign({}, optionsToSave);
  237. let markdown;
  238. if (editorMode === 'hackmd') {
  239. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  240. markdown = await pageEditorByHackmd.getMarkdown();
  241. // set option to sync
  242. options.isSyncRevisionToHackmd = true;
  243. revisionId = this.state.revisionIdHackmdSynced;
  244. }
  245. else {
  246. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  247. markdown = pageEditor.getMarkdown();
  248. }
  249. let res;
  250. if (pageId == null) {
  251. res = await this.createPage(path, markdown, options);
  252. }
  253. else {
  254. res = await this.updatePage(pageId, revisionId, markdown, options);
  255. }
  256. const editorContainer = this.appContainer.getContainer('EditorContainer');
  257. editorContainer.clearDraft(path);
  258. window.location.href = path;
  259. return res;
  260. }
  261. async createPage(pagePath, markdown, tmpParams) {
  262. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  263. // clone
  264. const params = Object.assign(tmpParams, {
  265. socketClientId: websocketContainer.getSocketClientId(),
  266. path: pagePath,
  267. body: markdown,
  268. });
  269. const res = await this.appContainer.apiPost('/pages.create', params);
  270. if (!res.ok) {
  271. throw new Error(res.error);
  272. }
  273. return { page: res.page, tags: res.tags };
  274. }
  275. async updatePage(pageId, revisionId, markdown, tmpParams) {
  276. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  277. // clone
  278. const params = Object.assign(tmpParams, {
  279. socketClientId: websocketContainer.getSocketClientId(),
  280. page_id: pageId,
  281. revision_id: revisionId,
  282. body: markdown,
  283. });
  284. const res = await this.appContainer.apiPost('/pages.update', params);
  285. if (!res.ok) {
  286. throw new Error(res.error);
  287. }
  288. return { page: res.page, tags: res.tags };
  289. }
  290. deletePage(isRecursively, isCompletely) {
  291. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  292. // control flag
  293. const completely = isCompletely ? true : null;
  294. const recursively = isRecursively ? true : null;
  295. return this.appContainer.apiPost('/pages.remove', {
  296. recursively,
  297. completely,
  298. page_id: this.state.pageId,
  299. revision_id: this.state.revisionId,
  300. socketClientId: websocketContainer.getSocketClientId(),
  301. });
  302. }
  303. revertRemove(isRecursively) {
  304. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  305. // control flag
  306. const recursively = isRecursively ? true : null;
  307. return this.appContainer.apiPost('/pages.revertRemove', {
  308. recursively,
  309. page_id: this.state.pageId,
  310. socketClientId: websocketContainer.getSocketClientId(),
  311. });
  312. }
  313. rename(pageNameInput, isRenameRecursively, isRenameRedirect, isRenameMetadata) {
  314. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  315. const isRecursively = isRenameRecursively ? true : null;
  316. const isRedirect = isRenameRedirect ? true : null;
  317. const isRemain = isRenameMetadata ? true : null;
  318. return this.appContainer.apiPost('/pages.rename', {
  319. recursively: isRecursively,
  320. page_id: this.state.pageId,
  321. revision_id: this.state.revisionId,
  322. new_path: pageNameInput,
  323. create_redirect: isRedirect,
  324. remain_metadata: isRemain,
  325. socketClientId: websocketContainer.getSocketClientId(),
  326. });
  327. }
  328. showSuccessToastr() {
  329. toastr.success(undefined, 'Saved successfully', {
  330. closeButton: true,
  331. progressBar: true,
  332. newestOnTop: false,
  333. showDuration: '100',
  334. hideDuration: '100',
  335. timeOut: '1200',
  336. extendedTimeOut: '150',
  337. });
  338. }
  339. showErrorToastr(error) {
  340. toastr.error(error.message, 'Error occured', {
  341. closeButton: true,
  342. progressBar: true,
  343. newestOnTop: false,
  344. showDuration: '100',
  345. hideDuration: '100',
  346. timeOut: '3000',
  347. });
  348. }
  349. addWebSocketEventHandlers() {
  350. const pageContainer = this;
  351. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  352. const socket = websocketContainer.getWebSocket();
  353. socket.on('page:create', (data) => {
  354. // skip if triggered myself
  355. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  356. return;
  357. }
  358. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  359. // update PageStatusAlert
  360. if (data.page.path === pageContainer.state.path) {
  361. this.setLatestRemotePageData(data.page, data.user);
  362. }
  363. });
  364. socket.on('page:update', (data) => {
  365. // skip if triggered myself
  366. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  367. return;
  368. }
  369. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  370. if (data.page.path === pageContainer.state.path) {
  371. // update PageStatusAlert
  372. pageContainer.setLatestRemotePageData(data.page, data.user);
  373. // update remote data
  374. const page = data.page;
  375. pageContainer.setState({
  376. remoteRevisionId: page.revision._id,
  377. revisionIdHackmdSynced: page.revisionHackmdSynced,
  378. hasDraftOnHackmd: page.hasDraftOnHackmd,
  379. });
  380. }
  381. });
  382. socket.on('page:delete', (data) => {
  383. // skip if triggered myself
  384. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  385. return;
  386. }
  387. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  388. // update PageStatusAlert
  389. if (data.page.path === pageContainer.state.path) {
  390. pageContainer.setLatestRemotePageData(data.page, data.user);
  391. }
  392. });
  393. socket.on('page:editingWithHackmd', (data) => {
  394. // skip if triggered myself
  395. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  396. return;
  397. }
  398. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  399. if (data.page.path === pageContainer.state.path) {
  400. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  401. }
  402. });
  403. }
  404. }