PageContainer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. import { Container } from 'unstated';
  2. import * as entities from 'entities';
  3. import * as toastr from 'toastr';
  4. import { pagePathUtils } from '@growi/core';
  5. import loggerFactory from '~/utils/logger';
  6. import { toastError } from '../util/apiNotification';
  7. import {
  8. DetachCodeBlockInterceptor,
  9. RestoreCodeBlockInterceptor,
  10. } from '../util/interceptor/detach-code-blocks';
  11. import {
  12. DrawioInterceptor,
  13. } from '../util/interceptor/drawio-interceptor';
  14. const { isTrashPage } = pagePathUtils;
  15. const logger = loggerFactory('growi:services:PageContainer');
  16. /**
  17. * Service container related to Page
  18. * @extends {Container} unstated Container
  19. */
  20. export default class PageContainer extends Container {
  21. constructor(appContainer) {
  22. super();
  23. this.appContainer = appContainer;
  24. this.appContainer.registerContainer(this);
  25. this.state = {};
  26. const mainContent = document.querySelector('#content-main');
  27. if (mainContent == null) {
  28. logger.debug('#content-main element is not exists');
  29. return;
  30. }
  31. const revisionId = mainContent.getAttribute('data-page-revision-id');
  32. const path = decodeURI(mainContent.getAttribute('data-path'));
  33. this.state = {
  34. // local page data
  35. markdown: null, // will be initialized after initStateMarkdown()
  36. pageId: mainContent.getAttribute('data-page-id'),
  37. revisionId,
  38. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  39. path,
  40. tocHtml: '',
  41. isLiked: false,
  42. isBookmarked: false,
  43. seenUsers: [],
  44. seenUserIds: mainContent.getAttribute('data-page-ids-of-seen-users'),
  45. countOfSeenUsers: mainContent.getAttribute('data-page-count-of-seen-users'),
  46. likerUsers: [],
  47. sumOfLikers: 0,
  48. sumOfBookmarks: 0,
  49. createdAt: mainContent.getAttribute('data-page-created-at'),
  50. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  51. deletedAt: mainContent.getAttribute('data-page-deleted-at') || null,
  52. isUserPage: JSON.parse(mainContent.getAttribute('data-page-user')) != null,
  53. isTrashPage: isTrashPage(path),
  54. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  55. isDeletable: JSON.parse(mainContent.getAttribute('data-page-is-deletable')),
  56. isNotCreatable: JSON.parse(mainContent.getAttribute('data-page-is-not-creatable')),
  57. isAbleToDeleteCompletely: JSON.parse(mainContent.getAttribute('data-page-is-able-to-delete-completely')),
  58. isPageExist: mainContent.getAttribute('data-page-id') != null,
  59. pageUser: JSON.parse(mainContent.getAttribute('data-page-user')),
  60. tags: null,
  61. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  62. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  63. shareLinksNumber: mainContent.getAttribute('data-share-links-number'),
  64. shareLinkId: JSON.parse(mainContent.getAttribute('data-share-link-id') || null),
  65. // latest(on remote) information
  66. remoteRevisionId: revisionId,
  67. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  68. lastUpdateUsername: mainContent.getAttribute('data-page-last-update-username') || null,
  69. deleteUsername: mainContent.getAttribute('data-page-delete-username') || null,
  70. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  71. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  72. isHackmdDraftUpdatingInRealtime: false,
  73. };
  74. // parse creator, lastUpdateUser and revisionAuthor
  75. try {
  76. this.state.creator = JSON.parse(mainContent.getAttribute('data-page-creator'));
  77. }
  78. catch (e) {
  79. logger.warn('The data of \'data-page-creator\' is invalid', e);
  80. }
  81. try {
  82. this.state.revisionAuthor = JSON.parse(mainContent.getAttribute('data-page-revision-author'));
  83. }
  84. catch (e) {
  85. logger.warn('The data of \'data-page-revision-author\' is invalid', e);
  86. }
  87. const { interceptorManager } = this.appContainer;
  88. interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(appContainer), 10); // process as soon as possible
  89. interceptorManager.addInterceptor(new DrawioInterceptor(appContainer), 20);
  90. interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(appContainer), 900); // process as late as possible
  91. this.initStateMarkdown();
  92. this.checkAndUpdateImageUrlCached(this.state.likerUsers);
  93. const { isSharedUser } = this.appContainer;
  94. // see https://dev.growi.org/5fabddf8bbeb1a0048bcb9e9
  95. const isAbleToGetAttachedInformationAboutPages = this.state.isPageExist && !isSharedUser;
  96. if (isAbleToGetAttachedInformationAboutPages) {
  97. this.retrieveSeenUsers();
  98. this.retrieveLikeInfo();
  99. this.retrieveBookmarkInfo();
  100. }
  101. this.setTocHtml = this.setTocHtml.bind(this);
  102. this.save = this.save.bind(this);
  103. this.checkAndUpdateImageUrlCached = this.checkAndUpdateImageUrlCached.bind(this);
  104. this.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  105. this.addWebSocketEventHandlers();
  106. const unlinkPageButton = document.getElementById('unlink-page-button');
  107. if (unlinkPageButton != null) {
  108. unlinkPageButton.addEventListener('click', async() => {
  109. try {
  110. const res = await this.appContainer.apiPost('/pages.unlink', { path });
  111. window.location.href = encodeURI(`${res.path}?unlinked=true`);
  112. }
  113. catch (err) {
  114. toastError(err);
  115. }
  116. });
  117. }
  118. }
  119. /**
  120. * Workaround for the mangling in production build to break constructor.name
  121. */
  122. static getClassName() {
  123. return 'PageContainer';
  124. }
  125. get isAbleToOpenPageEditor() {
  126. const { isNotCreatable, isTrashPage } = this.state;
  127. const { isGuestUser } = this.appContainer;
  128. return (!isNotCreatable && !isTrashPage && !isGuestUser);
  129. }
  130. /**
  131. * whether to display reaction buttons
  132. * ex.) like, bookmark
  133. */
  134. get isAbleToShowPageReactionButtons() {
  135. const { isTrashPage, isPageExist } = this.state;
  136. const { isSharedUser } = this.appContainer;
  137. return (!isTrashPage && isPageExist && !isSharedUser);
  138. }
  139. /**
  140. * whether to display tag labels
  141. */
  142. get isAbleToShowTagLabel() {
  143. const { isUserPage } = this.state;
  144. const { isSharedUser } = this.appContainer;
  145. return (!isUserPage && !isSharedUser);
  146. }
  147. /**
  148. * whether to display page management
  149. * ex.) duplicate, rename
  150. */
  151. get isAbleToShowPageManagement() {
  152. const { isPageExist, isTrashPage } = this.state;
  153. const { isSharedUser } = this.appContainer;
  154. return (isPageExist && !isTrashPage && !isSharedUser);
  155. }
  156. /**
  157. * whether to display pageEditorModeManager
  158. * ex.) view, edit, hackmd
  159. */
  160. get isAbleToShowPageEditorModeManager() {
  161. const { isNotCreatable, isTrashPage } = this.state;
  162. const { isSharedUser } = this.appContainer;
  163. return (!isNotCreatable && !isTrashPage && !isSharedUser);
  164. }
  165. /**
  166. * whether to display pageAuthors
  167. * ex.) creator, lastUpdateUser
  168. */
  169. get isAbleToShowPageAuthors() {
  170. const { isPageExist, isUserPage } = this.state;
  171. return (isPageExist && !isUserPage);
  172. }
  173. /**
  174. * whether to like button
  175. * not displayed on user page
  176. */
  177. get isAbleToShowLikeButton() {
  178. const { isUserPage } = this.state;
  179. const { isSharedUser } = this.appContainer;
  180. return (!isUserPage && !isSharedUser);
  181. }
  182. /**
  183. * whether to Empty Trash Page
  184. * not displayed when guest user and not on trash page
  185. */
  186. get isAbleToShowEmptyTrashButton() {
  187. const { currentUser } = this.appContainer;
  188. const { path, hasChildren } = this.state;
  189. return (currentUser != null && currentUser.admin && path === '/trash' && hasChildren);
  190. }
  191. /**
  192. * whether to display trash management buttons
  193. * ex.) undo, delete completly
  194. * not displayed when guest user
  195. */
  196. get isAbleToShowTrashPageManagementButtons() {
  197. const { currentUser } = this.appContainer;
  198. const { isDeleted } = this.state;
  199. return (isDeleted && currentUser != null);
  200. }
  201. /**
  202. * initialize state for markdown data
  203. */
  204. initStateMarkdown() {
  205. let pageContent = '';
  206. const rawText = document.getElementById('raw-text-original');
  207. if (rawText) {
  208. pageContent = rawText.innerHTML;
  209. }
  210. const markdown = entities.decodeHTML(pageContent);
  211. this.state.markdown = markdown;
  212. }
  213. async retrieveSeenUsers() {
  214. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: this.state.seenUserIds });
  215. this.setState({ seenUsers: users });
  216. this.checkAndUpdateImageUrlCached(users);
  217. }
  218. async retrieveLikeInfo() {
  219. const res = await this.appContainer.apiv3Get('/page/like-info', { _id: this.state.pageId });
  220. const { sumOfLikers, isLiked } = res.data;
  221. this.setState({
  222. sumOfLikers,
  223. isLiked,
  224. });
  225. }
  226. async toggleLike() {
  227. const bool = !this.state.isLiked;
  228. await this.appContainer.apiv3Put('/page/likes', { pageId: this.state.pageId, bool });
  229. this.setState({ isLiked: bool });
  230. return this.retrieveLikeInfo();
  231. }
  232. async retrieveBookmarkInfo() {
  233. const response = await this.appContainer.apiv3Get('/bookmarks/info', { pageId: this.state.pageId });
  234. this.setState({
  235. sumOfBookmarks: response.data.sumOfBookmarks,
  236. isBookmarked: response.data.isBookmarked,
  237. });
  238. }
  239. async toggleBookmark() {
  240. const bool = !this.state.isBookmarked;
  241. await this.appContainer.apiv3Put('/bookmarks', { pageId: this.state.pageId, bool });
  242. return this.retrieveBookmarkInfo();
  243. }
  244. async checkAndUpdateImageUrlCached(users) {
  245. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  246. if (noImageCacheUsers.length === 0) {
  247. return;
  248. }
  249. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  250. try {
  251. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  252. }
  253. catch (err) {
  254. // Error alert doesn't apear, because user don't need to notice this error.
  255. logger.error(err);
  256. }
  257. }
  258. get navigationContainer() {
  259. return this.appContainer.getContainer('NavigationContainer');
  260. }
  261. setLatestRemotePageData(s2cMessagePageUpdated) {
  262. const newState = {
  263. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  264. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  265. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  266. };
  267. if (s2cMessagePageUpdated.hasDraftOnHackmd != null) {
  268. newState.hasDraftOnHackmd = s2cMessagePageUpdated.hasDraftOnHackmd;
  269. }
  270. this.setState(newState);
  271. }
  272. setTocHtml(tocHtml) {
  273. if (this.state.tocHtml !== tocHtml) {
  274. this.setState({ tocHtml });
  275. }
  276. }
  277. /**
  278. * save success handler
  279. * @param {object} page Page instance
  280. * @param {Array[Tag]} tags Array of Tag
  281. * @param {object} revision Revision instance
  282. */
  283. updateStateAfterSave(page, tags, revision) {
  284. const { editorMode } = this.navigationContainer.state;
  285. // update state of PageContainer
  286. const newState = {
  287. pageId: page._id,
  288. revisionId: revision._id,
  289. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  290. remoteRevisionId: revision._id,
  291. revisionIdHackmdSynced: page.revisionHackmdSynced,
  292. hasDraftOnHackmd: page.hasDraftOnHackmd,
  293. markdown: revision.body,
  294. createdAt: page.createdAt,
  295. updatedAt: page.updatedAt,
  296. };
  297. if (tags != null) {
  298. newState.tags = tags;
  299. }
  300. this.setState(newState);
  301. // PageEditor component
  302. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  303. if (pageEditor != null) {
  304. if (editorMode !== 'edit') {
  305. pageEditor.updateEditorValue(newState.markdown);
  306. }
  307. }
  308. // PageEditorByHackmd component
  309. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  310. if (pageEditorByHackmd != null) {
  311. // reset
  312. if (editorMode !== 'hackmd') {
  313. pageEditorByHackmd.reset();
  314. }
  315. }
  316. // hidden input
  317. $('input[name="revision_id"]').val(newState.revisionId);
  318. }
  319. /**
  320. * Save page
  321. * @param {string} markdown
  322. * @param {object} optionsToSave
  323. * @return {object} { page: Page, tags: Tag[] }
  324. */
  325. async save(markdown, optionsToSave = {}) {
  326. const { editorMode } = this.navigationContainer.state;
  327. const { pageId, path } = this.state;
  328. let { revisionId } = this.state;
  329. const options = Object.assign({}, optionsToSave);
  330. if (editorMode === 'hackmd') {
  331. // set option to sync
  332. options.isSyncRevisionToHackmd = true;
  333. revisionId = this.state.revisionIdHackmdSynced;
  334. }
  335. let res;
  336. if (pageId == null) {
  337. res = await this.createPage(path, markdown, options);
  338. }
  339. else {
  340. res = await this.updatePage(pageId, revisionId, markdown, options);
  341. }
  342. this.updateStateAfterSave(res.page, res.tags, res.revision);
  343. return res;
  344. }
  345. async saveAndReload(optionsToSave) {
  346. if (optionsToSave == null) {
  347. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  348. throw new Error(msg);
  349. }
  350. const { editorMode } = this.navigationContainer.state;
  351. if (editorMode == null) {
  352. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  353. return;
  354. }
  355. const { pageId, path } = this.state;
  356. let { revisionId } = this.state;
  357. const options = Object.assign({}, optionsToSave);
  358. let markdown;
  359. if (editorMode === 'hackmd') {
  360. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  361. markdown = await pageEditorByHackmd.getMarkdown();
  362. // set option to sync
  363. options.isSyncRevisionToHackmd = true;
  364. revisionId = this.state.revisionIdHackmdSynced;
  365. }
  366. else {
  367. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  368. markdown = pageEditor.getMarkdown();
  369. }
  370. let res;
  371. if (pageId == null) {
  372. res = await this.createPage(path, markdown, options);
  373. }
  374. else {
  375. res = await this.updatePage(pageId, revisionId, markdown, options);
  376. }
  377. const editorContainer = this.appContainer.getContainer('EditorContainer');
  378. editorContainer.clearDraft(path);
  379. window.location.href = path;
  380. return res;
  381. }
  382. async createPage(pagePath, markdown, tmpParams) {
  383. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  384. // clone
  385. const params = Object.assign(tmpParams, {
  386. socketClientId: socketIoContainer.getSocketClientId(),
  387. path: pagePath,
  388. body: markdown,
  389. });
  390. const res = await this.appContainer.apiv3Post('/pages/', params);
  391. const { page, tags, revision } = res.data;
  392. return { page, tags, revision };
  393. }
  394. async updatePage(pageId, revisionId, markdown, tmpParams) {
  395. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  396. // clone
  397. const params = Object.assign(tmpParams, {
  398. socketClientId: socketIoContainer.getSocketClientId(),
  399. page_id: pageId,
  400. revision_id: revisionId,
  401. body: markdown,
  402. });
  403. const res = await this.appContainer.apiPost('/pages.update', params);
  404. if (!res.ok) {
  405. throw new Error(res.error);
  406. }
  407. return res;
  408. }
  409. deletePage(isRecursively, isCompletely) {
  410. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  411. // control flag
  412. const completely = isCompletely ? true : null;
  413. const recursively = isRecursively ? true : null;
  414. return this.appContainer.apiPost('/pages.remove', {
  415. recursively,
  416. completely,
  417. page_id: this.state.pageId,
  418. revision_id: this.state.revisionId,
  419. socketClientId: socketIoContainer.getSocketClientId(),
  420. });
  421. }
  422. revertRemove(isRecursively) {
  423. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  424. // control flag
  425. const recursively = isRecursively ? true : null;
  426. return this.appContainer.apiPost('/pages.revertRemove', {
  427. recursively,
  428. page_id: this.state.pageId,
  429. socketClientId: socketIoContainer.getSocketClientId(),
  430. });
  431. }
  432. rename(newPagePath, isRecursively, isRenameRedirect, isRemainMetadata) {
  433. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  434. const { pageId, revisionId, path } = this.state;
  435. return this.appContainer.apiv3Put('/pages/rename', {
  436. revisionId,
  437. pageId,
  438. isRecursively,
  439. isRenameRedirect,
  440. isRemainMetadata,
  441. newPagePath,
  442. path,
  443. socketClientId: socketIoContainer.getSocketClientId(),
  444. });
  445. }
  446. showSuccessToastr() {
  447. toastr.success(undefined, 'Saved successfully', {
  448. closeButton: true,
  449. progressBar: true,
  450. newestOnTop: false,
  451. showDuration: '100',
  452. hideDuration: '100',
  453. timeOut: '1200',
  454. extendedTimeOut: '150',
  455. });
  456. }
  457. showErrorToastr(error) {
  458. toastr.error(error.message, 'Error occured', {
  459. closeButton: true,
  460. progressBar: true,
  461. newestOnTop: false,
  462. showDuration: '100',
  463. hideDuration: '100',
  464. timeOut: '3000',
  465. });
  466. }
  467. addWebSocketEventHandlers() {
  468. // eslint-disable-next-line @typescript-eslint/no-this-alias
  469. const pageContainer = this;
  470. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  471. const socket = socketIoContainer.getSocket();
  472. socket.on('page:create', (data) => {
  473. // skip if triggered myself
  474. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  475. return;
  476. }
  477. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  478. // update remote page data
  479. const { s2cMessagePageUpdated } = data;
  480. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  481. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  482. }
  483. });
  484. socket.on('page:update', (data) => {
  485. // skip if triggered myself
  486. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  487. return;
  488. }
  489. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  490. // update remote page data
  491. const { s2cMessagePageUpdated } = data;
  492. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  493. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  494. }
  495. });
  496. socket.on('page:delete', (data) => {
  497. // skip if triggered myself
  498. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  499. return;
  500. }
  501. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  502. // update remote page data
  503. const { s2cMessagePageUpdated } = data;
  504. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  505. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  506. }
  507. });
  508. socket.on('page:editingWithHackmd', (data) => {
  509. // skip if triggered myself
  510. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  511. return;
  512. }
  513. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  514. // update isHackmdDraftUpdatingInRealtime
  515. const { s2cMessagePageUpdated } = data;
  516. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  517. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  518. }
  519. });
  520. }
  521. /* TODO GW-325 */
  522. retrieveMyBookmarkList() {
  523. }
  524. }