2
0

PageContainer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. * @param {object} revision Revision instance
  279. */
  280. updateStateAfterSave(page, tags, revision) {
  281. const { editorMode } = this.navigationContainer.state;
  282. // update state of PageContainer
  283. const newState = {
  284. pageId: page._id,
  285. revisionId: revision._id,
  286. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  287. remoteRevisionId: revision._id,
  288. revisionIdHackmdSynced: page.revisionHackmdSynced,
  289. hasDraftOnHackmd: page.hasDraftOnHackmd,
  290. markdown: revision.body,
  291. createdAt: page.createdAt,
  292. updatedAt: page.updatedAt,
  293. };
  294. if (tags != null) {
  295. newState.tags = tags;
  296. }
  297. this.setState(newState);
  298. // PageEditor component
  299. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  300. if (pageEditor != null) {
  301. if (editorMode !== 'edit') {
  302. pageEditor.updateEditorValue(newState.markdown);
  303. }
  304. }
  305. // PageEditorByHackmd component
  306. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  307. if (pageEditorByHackmd != null) {
  308. // reset
  309. if (editorMode !== 'hackmd') {
  310. pageEditorByHackmd.reset();
  311. }
  312. }
  313. // hidden input
  314. $('input[name="revision_id"]').val(newState.revisionId);
  315. }
  316. /**
  317. * Save page
  318. * @param {string} markdown
  319. * @param {object} optionsToSave
  320. * @return {object} { page: Page, tags: Tag[] }
  321. */
  322. async save(markdown, optionsToSave = {}) {
  323. const { editorMode } = this.navigationContainer.state;
  324. const { pageId, path } = this.state;
  325. let { revisionId } = this.state;
  326. const options = Object.assign({}, optionsToSave);
  327. if (editorMode === 'hackmd') {
  328. // set option to sync
  329. options.isSyncRevisionToHackmd = true;
  330. revisionId = this.state.revisionIdHackmdSynced;
  331. }
  332. let res;
  333. if (pageId == null) {
  334. res = await this.createPage(path, markdown, options);
  335. }
  336. else {
  337. res = await this.updatePage(pageId, revisionId, markdown, options);
  338. }
  339. this.updateStateAfterSave(res.page, res.tags, res.revision);
  340. return res;
  341. }
  342. async saveAndReload(optionsToSave) {
  343. if (optionsToSave == null) {
  344. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  345. throw new Error(msg);
  346. }
  347. const { editorMode } = this.navigationContainer.state;
  348. if (editorMode == null) {
  349. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  350. return;
  351. }
  352. const { pageId, path } = this.state;
  353. let { revisionId } = this.state;
  354. const options = Object.assign({}, optionsToSave);
  355. let markdown;
  356. if (editorMode === 'hackmd') {
  357. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  358. markdown = await pageEditorByHackmd.getMarkdown();
  359. // set option to sync
  360. options.isSyncRevisionToHackmd = true;
  361. revisionId = this.state.revisionIdHackmdSynced;
  362. }
  363. else {
  364. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  365. markdown = pageEditor.getMarkdown();
  366. }
  367. let res;
  368. if (pageId == null) {
  369. res = await this.createPage(path, markdown, options);
  370. }
  371. else {
  372. res = await this.updatePage(pageId, revisionId, markdown, options);
  373. }
  374. const editorContainer = this.appContainer.getContainer('EditorContainer');
  375. editorContainer.clearDraft(path);
  376. window.location.href = path;
  377. return res;
  378. }
  379. async createPage(pagePath, markdown, tmpParams) {
  380. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  381. // clone
  382. const params = Object.assign(tmpParams, {
  383. socketClientId: socketIoContainer.getSocketClientId(),
  384. path: pagePath,
  385. body: markdown,
  386. });
  387. const res = await this.appContainer.apiv3Post('/pages/', params);
  388. const { page, tags, revision } = res.data;
  389. return { page, tags, revision };
  390. }
  391. async updatePage(pageId, revisionId, markdown, tmpParams) {
  392. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  393. // clone
  394. const params = Object.assign(tmpParams, {
  395. socketClientId: socketIoContainer.getSocketClientId(),
  396. page_id: pageId,
  397. revision_id: revisionId,
  398. body: markdown,
  399. });
  400. const res = await this.appContainer.apiPost('/pages.update', params);
  401. if (!res.ok) {
  402. throw new Error(res.error);
  403. }
  404. return res;
  405. }
  406. deletePage(isRecursively, isCompletely) {
  407. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  408. // control flag
  409. const completely = isCompletely ? true : null;
  410. const recursively = isRecursively ? true : null;
  411. return this.appContainer.apiPost('/pages.remove', {
  412. recursively,
  413. completely,
  414. page_id: this.state.pageId,
  415. revision_id: this.state.revisionId,
  416. socketClientId: socketIoContainer.getSocketClientId(),
  417. });
  418. }
  419. revertRemove(isRecursively) {
  420. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  421. // control flag
  422. const recursively = isRecursively ? true : null;
  423. return this.appContainer.apiPost('/pages.revertRemove', {
  424. recursively,
  425. page_id: this.state.pageId,
  426. socketClientId: socketIoContainer.getSocketClientId(),
  427. });
  428. }
  429. rename(newPagePath, isRecursively, isRenameRedirect, isRemainMetadata) {
  430. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  431. const { pageId, revisionId, path } = this.state;
  432. return this.appContainer.apiv3Put('/pages/rename', {
  433. revisionId,
  434. pageId,
  435. isRecursively,
  436. isRenameRedirect,
  437. isRemainMetadata,
  438. newPagePath,
  439. path,
  440. socketClientId: socketIoContainer.getSocketClientId(),
  441. });
  442. }
  443. showSuccessToastr() {
  444. toastr.success(undefined, 'Saved successfully', {
  445. closeButton: true,
  446. progressBar: true,
  447. newestOnTop: false,
  448. showDuration: '100',
  449. hideDuration: '100',
  450. timeOut: '1200',
  451. extendedTimeOut: '150',
  452. });
  453. }
  454. showErrorToastr(error) {
  455. toastr.error(error.message, 'Error occured', {
  456. closeButton: true,
  457. progressBar: true,
  458. newestOnTop: false,
  459. showDuration: '100',
  460. hideDuration: '100',
  461. timeOut: '3000',
  462. });
  463. }
  464. addWebSocketEventHandlers() {
  465. const pageContainer = this;
  466. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  467. const socket = socketIoContainer.getSocket();
  468. socket.on('page:create', (data) => {
  469. // skip if triggered myself
  470. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  471. return;
  472. }
  473. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  474. // update remote page data
  475. const { s2cMessagePageUpdated } = data;
  476. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  477. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  478. }
  479. });
  480. socket.on('page:update', (data) => {
  481. // skip if triggered myself
  482. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  483. return;
  484. }
  485. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  486. // update remote page data
  487. const { s2cMessagePageUpdated } = data;
  488. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  489. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  490. }
  491. });
  492. socket.on('page:delete', (data) => {
  493. // skip if triggered myself
  494. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  495. return;
  496. }
  497. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  498. // update remote page data
  499. const { s2cMessagePageUpdated } = data;
  500. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  501. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  502. }
  503. });
  504. socket.on('page:editingWithHackmd', (data) => {
  505. // skip if triggered myself
  506. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  507. return;
  508. }
  509. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  510. // update isHackmdDraftUpdatingInRealtime
  511. const { s2cMessagePageUpdated } = data;
  512. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  513. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  514. }
  515. });
  516. }
  517. /* TODO GW-325 */
  518. retrieveMyBookmarkList() {
  519. }
  520. }