PageContainer.js 19 KB

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