PageContainer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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 { toastError } from '../util/apiNotification';
  6. const logger = loggerFactory('growi:services:PageContainer');
  7. const scrollThresForSticky = 0;
  8. const scrollThresForCompact = 30;
  9. const scrollThresForThrottling = 100;
  10. /**
  11. * Service container related to Page
  12. * @extends {Container} unstated Container
  13. */
  14. export default class PageContainer extends Container {
  15. constructor(appContainer) {
  16. super();
  17. this.appContainer = appContainer;
  18. this.appContainer.registerContainer(this);
  19. this.state = {};
  20. const mainContent = document.querySelector('#content-main');
  21. if (mainContent == null) {
  22. logger.debug('#content-main element is not exists');
  23. return;
  24. }
  25. const revisionId = mainContent.getAttribute('data-page-revision-id');
  26. const path = decodeURI(mainContent.getAttribute('data-path'));
  27. this.state = {
  28. // local page data
  29. markdown: null, // will be initialized after initStateMarkdown()
  30. pageId: mainContent.getAttribute('data-page-id'),
  31. revisionId,
  32. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  33. revisionAuthor: JSON.parse(mainContent.getAttribute('data-page-revision-author')),
  34. path,
  35. tocHtml: '',
  36. isLiked: JSON.parse(mainContent.getAttribute('data-page-is-liked')),
  37. seenUsers: [],
  38. likerUsers: [],
  39. sumOfSeenUsers: 0,
  40. sumOfLikers: 0,
  41. createdAt: mainContent.getAttribute('data-page-created-at'),
  42. creator: JSON.parse(mainContent.getAttribute('data-page-creator')),
  43. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  44. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  45. isDeletable: JSON.parse(mainContent.getAttribute('data-page-is-deletable')),
  46. isAbleToDeleteCompletely: JSON.parse(mainContent.getAttribute('data-page-is-able-to-delete-completely')),
  47. tags: [],
  48. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  49. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  50. // latest(on remote) information
  51. remoteRevisionId: revisionId,
  52. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  53. lastUpdateUsername: undefined,
  54. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  55. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  56. isHackmdDraftUpdatingInRealtime: false,
  57. isHeaderSticky: false,
  58. isSubnavCompact: false,
  59. };
  60. this.initStateMarkdown();
  61. this.initStateOthers();
  62. this.setTocHtml = this.setTocHtml.bind(this);
  63. this.save = this.save.bind(this);
  64. this.checkAndUpdateImageUrlCached = this.checkAndUpdateImageUrlCached.bind(this);
  65. this.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  66. this.addWebSocketEventHandlers();
  67. window.addEventListener('scroll', () => {
  68. const currentYOffset = window.pageYOffset;
  69. // original throttling
  70. if (this.state.isSubnavCompact && scrollThresForThrottling < currentYOffset) {
  71. return;
  72. }
  73. this.setState({
  74. isHeaderSticky: scrollThresForSticky < currentYOffset,
  75. isSubnavCompact: scrollThresForCompact < currentYOffset,
  76. });
  77. });
  78. const unlinkPageButton = document.getElementById('unlink-page-button');
  79. if (unlinkPageButton != null) {
  80. unlinkPageButton.addEventListener('click', async() => {
  81. try {
  82. const res = await this.appContainer.apiPost('/pages.unlink', { path });
  83. window.location.href = encodeURI(`${res.path}?unlinked=true`);
  84. }
  85. catch (err) {
  86. toastError(err);
  87. }
  88. });
  89. }
  90. }
  91. /**
  92. * Workaround for the mangling in production build to break constructor.name
  93. */
  94. static getClassName() {
  95. return 'PageContainer';
  96. }
  97. /**
  98. * initialize state for markdown data
  99. */
  100. initStateMarkdown() {
  101. let pageContent = '';
  102. const rawText = document.getElementById('raw-text-original');
  103. if (rawText) {
  104. pageContent = rawText.innerHTML;
  105. }
  106. const markdown = entities.decodeHTML(pageContent);
  107. this.state.markdown = markdown;
  108. }
  109. async initStateOthers() {
  110. const seenUserListElem = document.getElementById('seen-user-list');
  111. if (seenUserListElem != null) {
  112. const { userIdsStr, sumOfSeenUsers } = seenUserListElem.dataset;
  113. this.setState({ sumOfSeenUsers });
  114. if (userIdsStr === '') {
  115. return;
  116. }
  117. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: userIdsStr });
  118. this.setState({ seenUsers: users });
  119. this.checkAndUpdateImageUrlCached(users);
  120. }
  121. const likerListElem = document.getElementById('liker-list');
  122. if (likerListElem != null) {
  123. const { userIdsStr, sumOfLikers } = likerListElem.dataset;
  124. this.setState({ sumOfLikers });
  125. if (userIdsStr === '') {
  126. return;
  127. }
  128. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: userIdsStr });
  129. this.setState({ likerUsers: users });
  130. this.checkAndUpdateImageUrlCached(users);
  131. }
  132. }
  133. async checkAndUpdateImageUrlCached(users) {
  134. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  135. if (noImageCacheUsers.length === 0) {
  136. return;
  137. }
  138. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  139. try {
  140. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  141. }
  142. catch (err) {
  143. // Error alert doesn't apear, because user don't need to notice this error.
  144. logger.error(err);
  145. }
  146. }
  147. setLatestRemotePageData(page, user) {
  148. this.setState({
  149. remoteRevisionId: page.revision._id,
  150. revisionIdHackmdSynced: page.revisionHackmdSynced,
  151. lastUpdateUsername: user.name,
  152. });
  153. }
  154. setTocHtml(tocHtml) {
  155. if (this.state.tocHtml !== tocHtml) {
  156. this.setState({ tocHtml });
  157. }
  158. }
  159. /**
  160. * save success handler
  161. * @param {object} page Page instance
  162. * @param {Array[Tag]} tags Array of Tag
  163. */
  164. updateStateAfterSave(page, tags) {
  165. const { editorMode } = this.appContainer.state;
  166. // update state of PageContainer
  167. const newState = {
  168. pageId: page._id,
  169. revisionId: page.revision._id,
  170. revisionCreatedAt: new Date(page.revision.createdAt).getTime() / 1000,
  171. remoteRevisionId: page.revision._id,
  172. revisionIdHackmdSynced: page.revisionHackmdSynced,
  173. hasDraftOnHackmd: page.hasDraftOnHackmd,
  174. markdown: page.revision.body,
  175. };
  176. if (tags != null) {
  177. newState.tags = tags;
  178. }
  179. this.setState(newState);
  180. // PageEditor component
  181. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  182. if (pageEditor != null) {
  183. if (editorMode !== 'builtin') {
  184. pageEditor.updateEditorValue(newState.markdown);
  185. }
  186. }
  187. // PageEditorByHackmd component
  188. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  189. if (pageEditorByHackmd != null) {
  190. // reset
  191. if (editorMode !== 'hackmd') {
  192. pageEditorByHackmd.reset();
  193. }
  194. }
  195. // hidden input
  196. $('input[name="revision_id"]').val(newState.revisionId);
  197. }
  198. /**
  199. * Save page
  200. * @param {string} markdown
  201. * @param {object} optionsToSave
  202. * @return {object} { page: Page, tags: Tag[] }
  203. */
  204. async save(markdown, optionsToSave = {}) {
  205. const { editorMode } = this.appContainer.state;
  206. const { pageId, path } = this.state;
  207. let { revisionId } = this.state;
  208. const options = Object.assign({}, optionsToSave);
  209. if (editorMode === 'hackmd') {
  210. // set option to sync
  211. options.isSyncRevisionToHackmd = true;
  212. revisionId = this.state.revisionIdHackmdSynced;
  213. }
  214. let res;
  215. if (pageId == null) {
  216. res = await this.createPage(path, markdown, options);
  217. }
  218. else {
  219. res = await this.updatePage(pageId, revisionId, markdown, options);
  220. }
  221. this.updateStateAfterSave(res.page, res.tags);
  222. return res;
  223. }
  224. async saveAndReload(optionsToSave) {
  225. if (optionsToSave == null) {
  226. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  227. throw new Error(msg);
  228. }
  229. const { editorMode } = this.appContainer.state;
  230. if (editorMode == null) {
  231. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  232. return;
  233. }
  234. const { pageId, path } = this.state;
  235. let { revisionId } = this.state;
  236. const options = Object.assign({}, optionsToSave);
  237. let markdown;
  238. if (editorMode === 'hackmd') {
  239. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  240. markdown = await pageEditorByHackmd.getMarkdown();
  241. // set option to sync
  242. options.isSyncRevisionToHackmd = true;
  243. revisionId = this.state.revisionIdHackmdSynced;
  244. }
  245. else {
  246. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  247. markdown = pageEditor.getMarkdown();
  248. }
  249. let res;
  250. if (pageId == null) {
  251. res = await this.createPage(path, markdown, options);
  252. }
  253. else {
  254. res = await this.updatePage(pageId, revisionId, markdown, options);
  255. }
  256. const editorContainer = this.appContainer.getContainer('EditorContainer');
  257. editorContainer.clearDraft(path);
  258. window.location.href = path;
  259. return res;
  260. }
  261. async createPage(pagePath, markdown, tmpParams) {
  262. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  263. // clone
  264. const params = Object.assign(tmpParams, {
  265. socketClientId: websocketContainer.getSocketClientId(),
  266. path: pagePath,
  267. body: markdown,
  268. });
  269. const res = await this.appContainer.apiPost('/pages.create', params);
  270. if (!res.ok) {
  271. throw new Error(res.error);
  272. }
  273. return { page: res.page, tags: res.tags };
  274. }
  275. async updatePage(pageId, revisionId, markdown, tmpParams) {
  276. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  277. // clone
  278. const params = Object.assign(tmpParams, {
  279. socketClientId: websocketContainer.getSocketClientId(),
  280. page_id: pageId,
  281. revision_id: revisionId,
  282. body: markdown,
  283. });
  284. const res = await this.appContainer.apiPost('/pages.update', params);
  285. if (!res.ok) {
  286. throw new Error(res.error);
  287. }
  288. return { page: res.page, tags: res.tags };
  289. }
  290. deletePage(isRecursively, isCompletely) {
  291. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  292. // control flag
  293. const completely = isCompletely ? true : null;
  294. const recursively = isRecursively ? true : null;
  295. return this.appContainer.apiPost('/pages.remove', {
  296. recursively,
  297. completely,
  298. page_id: this.state.pageId,
  299. revision_id: this.state.revisionId,
  300. socketClientId: websocketContainer.getSocketClientId(),
  301. });
  302. }
  303. revertRemove(isRecursively) {
  304. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  305. // control flag
  306. const recursively = isRecursively ? true : null;
  307. return this.appContainer.apiPost('/pages.revertRemove', {
  308. recursively,
  309. page_id: this.state.pageId,
  310. socketClientId: websocketContainer.getSocketClientId(),
  311. });
  312. }
  313. rename(pageNameInput, isRenameRecursively, isRenameRedirect, isRenameMetadata) {
  314. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  315. const isRecursively = isRenameRecursively ? true : null;
  316. const isRedirect = isRenameRedirect ? true : null;
  317. const isRemain = isRenameMetadata ? true : null;
  318. return this.appContainer.apiPost('/pages.rename', {
  319. recursively: isRecursively,
  320. page_id: this.state.pageId,
  321. revision_id: this.state.revisionId,
  322. new_path: pageNameInput,
  323. create_redirect: isRedirect,
  324. remain_metadata: isRemain,
  325. socketClientId: websocketContainer.getSocketClientId(),
  326. });
  327. }
  328. showSuccessToastr() {
  329. toastr.success(undefined, 'Saved successfully', {
  330. closeButton: true,
  331. progressBar: true,
  332. newestOnTop: false,
  333. showDuration: '100',
  334. hideDuration: '100',
  335. timeOut: '1200',
  336. extendedTimeOut: '150',
  337. });
  338. }
  339. showErrorToastr(error) {
  340. toastr.error(error.message, 'Error occured', {
  341. closeButton: true,
  342. progressBar: true,
  343. newestOnTop: false,
  344. showDuration: '100',
  345. hideDuration: '100',
  346. timeOut: '3000',
  347. });
  348. }
  349. addWebSocketEventHandlers() {
  350. const pageContainer = this;
  351. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  352. const socket = websocketContainer.getWebSocket();
  353. socket.on('page:create', (data) => {
  354. // skip if triggered myself
  355. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  356. return;
  357. }
  358. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  359. // update PageStatusAlert
  360. if (data.page.path === pageContainer.state.path) {
  361. this.setLatestRemotePageData(data.page, data.user);
  362. }
  363. });
  364. socket.on('page:update', (data) => {
  365. // skip if triggered myself
  366. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  367. return;
  368. }
  369. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  370. if (data.page.path === pageContainer.state.path) {
  371. // update PageStatusAlert
  372. pageContainer.setLatestRemotePageData(data.page, data.user);
  373. // update remote data
  374. const page = data.page;
  375. pageContainer.setState({
  376. remoteRevisionId: page.revision._id,
  377. revisionIdHackmdSynced: page.revisionHackmdSynced,
  378. hasDraftOnHackmd: page.hasDraftOnHackmd,
  379. });
  380. }
  381. });
  382. socket.on('page:delete', (data) => {
  383. // skip if triggered myself
  384. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  385. return;
  386. }
  387. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  388. // update PageStatusAlert
  389. if (data.page.path === pageContainer.state.path) {
  390. pageContainer.setLatestRemotePageData(data.page, data.user);
  391. }
  392. });
  393. socket.on('page:editingWithHackmd', (data) => {
  394. // skip if triggered myself
  395. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  396. return;
  397. }
  398. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  399. if (data.page.path === pageContainer.state.path) {
  400. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  401. }
  402. });
  403. }
  404. }