PageContainer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. isTrashPage: isTrashPage(path),
  51. isForbidden: JSON.parse(mainContent.getAttribute('data-page-is-forbidden')),
  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 { currentUser } = this.appContainer;
  91. // check what kind of user
  92. this.state.isGuestUser = currentUser == null;
  93. this.state.isSharedUser = this.state.shareLinkId != null && currentUser == null;
  94. // see https://dev.growi.org/5fabddf8bbeb1a0048bcb9e9
  95. const isAbleToGetAttachedInformationAboutPages = this.state.isPageExist && !this.state.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 {
  127. isGuestUser, isPageForbidden, isNotCreatable, isTrashPage,
  128. } = this.state;
  129. return (!isGuestUser && !isPageForbidden && !isNotCreatable && !isTrashPage);
  130. }
  131. /**
  132. * whether to display reaction buttons
  133. * ex.) like, bookmark
  134. */
  135. get isAbleToShowPageReactionButtons() {
  136. const { isTrashPage, isPageExist, isSharedUser } = this.state;
  137. return (!isTrashPage && isPageExist && !isSharedUser);
  138. }
  139. /**
  140. * initialize state for markdown data
  141. */
  142. initStateMarkdown() {
  143. let pageContent = '';
  144. const rawText = document.getElementById('raw-text-original');
  145. if (rawText) {
  146. pageContent = rawText.innerHTML;
  147. }
  148. const markdown = entities.decodeHTML(pageContent);
  149. this.state.markdown = markdown;
  150. }
  151. async retrieveSeenUsers() {
  152. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: this.state.seenUserIds });
  153. this.setState({ seenUsers: users });
  154. this.checkAndUpdateImageUrlCached(users);
  155. }
  156. async retrieveLikeInfo() {
  157. const res = await this.appContainer.apiv3Get('/page/like-info', { _id: this.state.pageId });
  158. const { sumOfLikers, isLiked } = res.data;
  159. this.setState({
  160. sumOfLikers,
  161. isLiked,
  162. });
  163. }
  164. async toggleLike() {
  165. const bool = !this.state.isLiked;
  166. await this.appContainer.apiv3Put('/page/likes', { pageId: this.state.pageId, bool });
  167. this.setState({ isLiked: bool });
  168. return this.retrieveLikeInfo();
  169. }
  170. async retrieveBookmarkInfo() {
  171. const response = await this.appContainer.apiv3Get('/bookmarks/info', { pageId: this.state.pageId });
  172. this.setState({
  173. sumOfBookmarks: response.data.sumOfBookmarks,
  174. isBookmarked: response.data.isBookmarked,
  175. });
  176. }
  177. async toggleBookmark() {
  178. const bool = !this.state.isBookmarked;
  179. await this.appContainer.apiv3Put('/bookmarks', { pageId: this.state.pageId, bool });
  180. return this.retrieveBookmarkInfo();
  181. }
  182. async checkAndUpdateImageUrlCached(users) {
  183. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  184. if (noImageCacheUsers.length === 0) {
  185. return;
  186. }
  187. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  188. try {
  189. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  190. }
  191. catch (err) {
  192. // Error alert doesn't apear, because user don't need to notice this error.
  193. logger.error(err);
  194. }
  195. }
  196. get navigationContainer() {
  197. return this.appContainer.getContainer('NavigationContainer');
  198. }
  199. setLatestRemotePageData(page, user) {
  200. this.setState({
  201. remoteRevisionId: page.revision._id,
  202. revisionIdHackmdSynced: page.revisionHackmdSynced,
  203. lastUpdateUsername: user.name,
  204. });
  205. }
  206. setTocHtml(tocHtml) {
  207. if (this.state.tocHtml !== tocHtml) {
  208. this.setState({ tocHtml });
  209. }
  210. }
  211. /**
  212. * save success handler
  213. * @param {object} page Page instance
  214. * @param {Array[Tag]} tags Array of Tag
  215. */
  216. updateStateAfterSave(page, tags) {
  217. const { editorMode } = this.navigationContainer.state;
  218. // update state of PageContainer
  219. const newState = {
  220. pageId: page._id,
  221. revisionId: page.revision._id,
  222. revisionCreatedAt: new Date(page.revision.createdAt).getTime() / 1000,
  223. remoteRevisionId: page.revision._id,
  224. revisionIdHackmdSynced: page.revisionHackmdSynced,
  225. hasDraftOnHackmd: page.hasDraftOnHackmd,
  226. markdown: page.revision.body,
  227. createdAt: page.createdAt,
  228. updatedAt: page.updatedAt,
  229. };
  230. if (tags != null) {
  231. newState.tags = tags;
  232. }
  233. this.setState(newState);
  234. // PageEditor component
  235. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  236. if (pageEditor != null) {
  237. if (editorMode !== 'edit') {
  238. pageEditor.updateEditorValue(newState.markdown);
  239. }
  240. }
  241. // PageEditorByHackmd component
  242. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  243. if (pageEditorByHackmd != null) {
  244. // reset
  245. if (editorMode !== 'hackmd') {
  246. pageEditorByHackmd.reset();
  247. }
  248. }
  249. // hidden input
  250. $('input[name="revision_id"]').val(newState.revisionId);
  251. }
  252. /**
  253. * Save page
  254. * @param {string} markdown
  255. * @param {object} optionsToSave
  256. * @return {object} { page: Page, tags: Tag[] }
  257. */
  258. async save(markdown, optionsToSave = {}) {
  259. const { editorMode } = this.navigationContainer.state;
  260. const { pageId, path } = this.state;
  261. let { revisionId } = this.state;
  262. const options = Object.assign({}, optionsToSave);
  263. if (editorMode === 'hackmd') {
  264. // set option to sync
  265. options.isSyncRevisionToHackmd = true;
  266. revisionId = this.state.revisionIdHackmdSynced;
  267. }
  268. let res;
  269. if (pageId == null) {
  270. res = await this.createPage(path, markdown, options);
  271. }
  272. else {
  273. res = await this.updatePage(pageId, revisionId, markdown, options);
  274. }
  275. this.updateStateAfterSave(res.page, res.tags);
  276. return res;
  277. }
  278. async saveAndReload(optionsToSave) {
  279. if (optionsToSave == null) {
  280. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  281. throw new Error(msg);
  282. }
  283. const { editorMode } = this.navigationContainer.state;
  284. if (editorMode == null) {
  285. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  286. return;
  287. }
  288. const { pageId, path } = this.state;
  289. let { revisionId } = this.state;
  290. const options = Object.assign({}, optionsToSave);
  291. let markdown;
  292. if (editorMode === 'hackmd') {
  293. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  294. markdown = await pageEditorByHackmd.getMarkdown();
  295. // set option to sync
  296. options.isSyncRevisionToHackmd = true;
  297. revisionId = this.state.revisionIdHackmdSynced;
  298. }
  299. else {
  300. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  301. markdown = pageEditor.getMarkdown();
  302. }
  303. let res;
  304. if (pageId == null) {
  305. res = await this.createPage(path, markdown, options);
  306. }
  307. else {
  308. res = await this.updatePage(pageId, revisionId, markdown, options);
  309. }
  310. const editorContainer = this.appContainer.getContainer('EditorContainer');
  311. editorContainer.clearDraft(path);
  312. window.location.href = path;
  313. return res;
  314. }
  315. async createPage(pagePath, markdown, tmpParams) {
  316. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  317. // clone
  318. const params = Object.assign(tmpParams, {
  319. socketClientId: socketIoContainer.getSocketClientId(),
  320. path: pagePath,
  321. body: markdown,
  322. });
  323. const res = await this.appContainer.apiPost('/pages.create', params);
  324. if (!res.ok) {
  325. throw new Error(res.error);
  326. }
  327. return { page: res.page, tags: res.tags };
  328. }
  329. async updatePage(pageId, revisionId, markdown, tmpParams) {
  330. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  331. // clone
  332. const params = Object.assign(tmpParams, {
  333. socketClientId: socketIoContainer.getSocketClientId(),
  334. page_id: pageId,
  335. revision_id: revisionId,
  336. body: markdown,
  337. });
  338. const res = await this.appContainer.apiPost('/pages.update', params);
  339. if (!res.ok) {
  340. throw new Error(res.error);
  341. }
  342. return { page: res.page, tags: res.tags };
  343. }
  344. deletePage(isRecursively, isCompletely) {
  345. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  346. // control flag
  347. const completely = isCompletely ? true : null;
  348. const recursively = isRecursively ? true : null;
  349. return this.appContainer.apiPost('/pages.remove', {
  350. recursively,
  351. completely,
  352. page_id: this.state.pageId,
  353. revision_id: this.state.revisionId,
  354. socketClientId: socketIoContainer.getSocketClientId(),
  355. });
  356. }
  357. revertRemove(isRecursively) {
  358. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  359. // control flag
  360. const recursively = isRecursively ? true : null;
  361. return this.appContainer.apiPost('/pages.revertRemove', {
  362. recursively,
  363. page_id: this.state.pageId,
  364. socketClientId: socketIoContainer.getSocketClientId(),
  365. });
  366. }
  367. rename(pageNameInput, isRenameRecursively, isRenameRedirect, isRenameMetadata) {
  368. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  369. const isRecursively = isRenameRecursively ? true : null;
  370. const isRedirect = isRenameRedirect ? true : null;
  371. const isRemain = isRenameMetadata ? true : null;
  372. return this.appContainer.apiPost('/pages.rename', {
  373. recursively: isRecursively,
  374. page_id: this.state.pageId,
  375. revision_id: this.state.revisionId,
  376. new_path: pageNameInput,
  377. create_redirect: isRedirect,
  378. remain_metadata: isRemain,
  379. socketClientId: socketIoContainer.getSocketClientId(),
  380. });
  381. }
  382. showSuccessToastr() {
  383. toastr.success(undefined, 'Saved successfully', {
  384. closeButton: true,
  385. progressBar: true,
  386. newestOnTop: false,
  387. showDuration: '100',
  388. hideDuration: '100',
  389. timeOut: '1200',
  390. extendedTimeOut: '150',
  391. });
  392. }
  393. showErrorToastr(error) {
  394. toastr.error(error.message, 'Error occured', {
  395. closeButton: true,
  396. progressBar: true,
  397. newestOnTop: false,
  398. showDuration: '100',
  399. hideDuration: '100',
  400. timeOut: '3000',
  401. });
  402. }
  403. addWebSocketEventHandlers() {
  404. const pageContainer = this;
  405. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  406. const socket = socketIoContainer.getSocket();
  407. socket.on('page:create', (data) => {
  408. // skip if triggered myself
  409. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  410. return;
  411. }
  412. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  413. // update PageStatusAlert
  414. if (data.page.path === pageContainer.state.path) {
  415. this.setLatestRemotePageData(data.page, data.user);
  416. }
  417. });
  418. socket.on('page:update', (data) => {
  419. // skip if triggered myself
  420. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  421. return;
  422. }
  423. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  424. if (data.page.path === pageContainer.state.path) {
  425. // update PageStatusAlert
  426. pageContainer.setLatestRemotePageData(data.page, data.user);
  427. // update remote data
  428. const page = data.page;
  429. pageContainer.setState({
  430. remoteRevisionId: page.revision._id,
  431. revisionIdHackmdSynced: page.revisionHackmdSynced,
  432. hasDraftOnHackmd: page.hasDraftOnHackmd,
  433. });
  434. }
  435. });
  436. socket.on('page:delete', (data) => {
  437. // skip if triggered myself
  438. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  439. return;
  440. }
  441. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  442. // update PageStatusAlert
  443. if (data.page.path === pageContainer.state.path) {
  444. pageContainer.setLatestRemotePageData(data.page, data.user);
  445. }
  446. });
  447. socket.on('page:editingWithHackmd', (data) => {
  448. // skip if triggered myself
  449. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  450. return;
  451. }
  452. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  453. if (data.page.path === pageContainer.state.path) {
  454. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  455. }
  456. });
  457. }
  458. /* TODO GW-325 */
  459. retrieveMyBookmarkList() {
  460. }
  461. }