PageContainer.js 19 KB

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