PageContainer.js 14 KB

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