crowi.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /* jshint browser: true, jquery: true */
  2. /* Author: Sotaro KARASAWA <sotarok@crocos.co.jp>
  3. */
  4. /* global crowi: true */
  5. /* global crowiRenderer: true */
  6. import React from 'react';
  7. import ReactDOM from 'react-dom';
  8. import { debounce } from 'throttle-debounce';
  9. import GrowiRenderer from '../util/GrowiRenderer';
  10. import Page from '../components/Page';
  11. const io = require('socket.io-client');
  12. const entities = require('entities');
  13. const escapeStringRegexp = require('escape-string-regexp');
  14. require('jquery.cookie');
  15. require('bootstrap-select');
  16. require('./thirdparty-js/agile-admin');
  17. const pagePathUtil = require('../../../lib/util/pagePathUtil');
  18. let Crowi = {};
  19. if (!window) {
  20. window = {};
  21. }
  22. window.Crowi = Crowi;
  23. Crowi.createErrorView = function(msg) {
  24. $('#main').prepend($('<p class="alert-message error">' + msg + '</p>'));
  25. };
  26. /**
  27. * render Table Of Contents
  28. * @param {string} tocHtml
  29. */
  30. Crowi.renderTocContent = (tocHtml) => {
  31. $('#revision-toc-content').html(tocHtml);
  32. };
  33. /**
  34. * append buttons to section headers
  35. */
  36. Crowi.appendEditSectionButtons = function(parentElement) {
  37. $('h1,h2,h3,h4,h5,h6', parentElement).each(function(idx, elm) {
  38. const line = +elm.getAttribute('data-line');
  39. // add button
  40. $(this).append(`
  41. <span class="revision-head-edit-button">
  42. <a href="#edit" onClick="Crowi.setCaretLineData(${line})">
  43. <i class="icon-note"></i>
  44. </a>
  45. </span>
  46. `
  47. );
  48. });
  49. };
  50. /**
  51. * set 'data-caret-line' attribute that will be processed when 'shown.bs.tab' event fired
  52. * @param {number} line
  53. */
  54. Crowi.setCaretLineData = function(line) {
  55. const pageEditorDom = document.querySelector('#page-editor');
  56. pageEditorDom.setAttribute('data-caret-line', line);
  57. };
  58. /**
  59. * invoked when;
  60. *
  61. * 1. window loaded
  62. * 2. 'shown.bs.tab' event fired
  63. */
  64. Crowi.setCaretLineAndFocusToEditor = function() {
  65. // get 'data-caret-line' attributes
  66. const pageEditorDom = document.querySelector('#page-editor');
  67. if (pageEditorDom == null) {
  68. return;
  69. }
  70. const line = pageEditorDom.getAttribute('data-caret-line');
  71. if (line != null && !isNaN(line)) {
  72. crowi.setCaretLine(+line);
  73. // reset data-caret-line attribute
  74. pageEditorDom.removeAttribute('data-caret-line');
  75. }
  76. // focus
  77. crowi.focusToEditor();
  78. };
  79. // original: middleware.swigFilter
  80. Crowi.userPicture = function(user) {
  81. if (!user) {
  82. return '/images/icons/user.svg';
  83. }
  84. return user.image || '/images/icons/user.svg';
  85. };
  86. Crowi.modifyScrollTop = function() {
  87. var offset = 10;
  88. var hash = window.location.hash;
  89. if (hash === '') {
  90. return;
  91. }
  92. var pageHeader = document.querySelector('#page-header');
  93. if (!pageHeader) {
  94. return;
  95. }
  96. var pageHeaderRect = pageHeader.getBoundingClientRect();
  97. var sectionHeader = Crowi.findSectionHeader(hash);
  98. if (sectionHeader === null) {
  99. return;
  100. }
  101. var timeout = 0;
  102. if (window.scrollY === 0) {
  103. timeout = 200;
  104. }
  105. setTimeout(function() {
  106. var sectionHeaderRect = sectionHeader.getBoundingClientRect();
  107. if (sectionHeaderRect.top >= pageHeaderRect.bottom) {
  108. return;
  109. }
  110. window.scrollTo(0, (window.scrollY - pageHeaderRect.height - offset));
  111. }, timeout);
  112. };
  113. Crowi.updatePageForm = function(page) {
  114. $('#page-form [name="pageForm[currentRevision]"]').val(page.revision._id);
  115. $('#page-form [name="pageForm[grant]"]').val(page.grant);
  116. };
  117. Crowi.handleKeyEHandler = (event) => {
  118. // ignore when dom that has 'modal in' classes exists
  119. if (document.getElementsByClassName('modal in').length > 0) {
  120. return;
  121. }
  122. // show editor
  123. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  124. event.preventDefault();
  125. };
  126. Crowi.handleKeyCHandler = (event) => {
  127. // ignore when dom that has 'modal in' classes exists
  128. if (document.getElementsByClassName('modal in').length > 0) {
  129. return;
  130. }
  131. // show modal to create a page
  132. $('#create-page').modal();
  133. event.preventDefault();
  134. };
  135. Crowi.handleKeyCtrlSlashHandler = (event) => {
  136. // show modal to create a page
  137. $('#shortcuts-modal').modal('toggle');
  138. event.preventDefault();
  139. };
  140. Crowi.initSlimScrollForRevisionToc = () => {
  141. const revisionTocElem = document.querySelector('.growi .revision-toc');
  142. const tocContentElem = document.querySelector('.growi .revision-toc .markdownIt-TOC');
  143. // growi layout only
  144. if (revisionTocElem == null || tocContentElem == null) {
  145. return;
  146. }
  147. function getCurrentRevisionTocTop() {
  148. // calculate absolute top of '#revision-toc' element
  149. return revisionTocElem.getBoundingClientRect().top;
  150. }
  151. function resetScrollbar(revisionTocTop) {
  152. // window height - revisionTocTop - .system-version height
  153. let h = window.innerHeight - revisionTocTop - 20;
  154. const tocContentHeight = tocContentElem.getBoundingClientRect().height + 15; // add margin
  155. h = Math.min(h, tocContentHeight);
  156. $('#revision-toc-content').slimScroll({
  157. railVisible: true,
  158. position: 'right',
  159. height: h,
  160. });
  161. }
  162. const resetScrollbarDebounced = debounce(100, resetScrollbar);
  163. // initialize
  164. const revisionTocTop = getCurrentRevisionTocTop();
  165. resetScrollbar(revisionTocTop);
  166. /*
  167. * set event listener
  168. */
  169. // resize
  170. window.addEventListener('resize', (event) => {
  171. resetScrollbarDebounced(getCurrentRevisionTocTop());
  172. });
  173. // affix on
  174. $('#revision-toc').on('affixed.bs.affix', function() {
  175. resetScrollbar(getCurrentRevisionTocTop());
  176. });
  177. // affix off
  178. $('#revision-toc').on('affixed-top.bs.affix', function() {
  179. // calculate sum of height (.navbar-header + .bg-title) + margin-top of .main
  180. const sum = 138;
  181. resetScrollbar(sum);
  182. });
  183. };
  184. $(function() {
  185. var config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
  186. var pageId = $('#content-main').data('page-id');
  187. // var revisionId = $('#content-main').data('page-revision-id');
  188. // var revisionCreatedAt = $('#content-main').data('page-revision-created');
  189. // var currentUser = $('#content-main').data('current-user');
  190. var isSeen = $('#content-main').data('page-is-seen');
  191. var pagePath= $('#content-main').data('path');
  192. var isSavedStatesOfTabChanges = config['isSavedStatesOfTabChanges'];
  193. $('[data-toggle="popover"]').popover();
  194. $('[data-toggle="tooltip"]').tooltip();
  195. $('[data-tooltip-stay]').tooltip('show');
  196. $('#toggle-sidebar').click(function(e) {
  197. var $mainContainer = $('.main-container');
  198. if ($mainContainer.hasClass('aside-hidden')) {
  199. $('.main-container').removeClass('aside-hidden');
  200. $.cookie('aside-hidden', 0, { expires: 30, path: '/' });
  201. }
  202. else {
  203. $mainContainer.addClass('aside-hidden');
  204. $.cookie('aside-hidden', 1, { expires: 30, path: '/' });
  205. }
  206. return false;
  207. });
  208. if ($.cookie('aside-hidden') == 1) {
  209. $('.main-container').addClass('aside-hidden');
  210. }
  211. $('.copy-link').on('click', function() {
  212. $(this).select();
  213. });
  214. $('#create-page').on('shown.bs.modal', function(e) {
  215. // quick hack: replace from server side rendering "date" to client side "date"
  216. var today = new Date();
  217. var month = ('0' + (today.getMonth() + 1)).slice(-2);
  218. var day = ('0' + today.getDate()).slice(-2);
  219. var dateString = today.getFullYear() + '/' + month + '/' + day;
  220. $('#create-page-today .page-today-suffix').text('/' + dateString + '/');
  221. $('#create-page-today .page-today-input2').data('prefix', '/' + dateString + '/');
  222. // focus
  223. $('#create-page-today .page-today-input2').eq(0).focus();
  224. });
  225. $('#create-page-today').submit(function(e) {
  226. var prefix1 = $('input.page-today-input1', this).data('prefix');
  227. var input1 = $('input.page-today-input1', this).val();
  228. var prefix2 = $('input.page-today-input2', this).data('prefix');
  229. var input2 = $('input.page-today-input2', this).val();
  230. if (input1 === '') {
  231. prefix1 = 'メモ';
  232. }
  233. if (input2 === '') {
  234. prefix2 = prefix2.slice(0, -1);
  235. }
  236. top.location.href = prefix1 + input1 + prefix2 + input2 + '#edit';
  237. return false;
  238. });
  239. $('#create-page-under-tree').submit(function(e) {
  240. var name = $('input', this).val();
  241. if (!name.match(/^\//)) {
  242. name = '/' + name;
  243. }
  244. if (name.match(/.+\/$/)) {
  245. name = name.substr(0, name.length - 1);
  246. }
  247. top.location.href = pagePathUtil.encodePagePath(name) + '#edit';
  248. return false;
  249. });
  250. // rename/unportalize
  251. $('#renamePage, #unportalize').on('shown.bs.modal', function(e) {
  252. $('#renamePage #newPageName').focus();
  253. $('#renamePage .msg-already-exists, #unportalize .msg-already-exists').hide();
  254. });
  255. $('#renamePageForm, #unportalize-form').submit(function(e) {
  256. // create name-value map
  257. let nameValueMap = {};
  258. $(this).serializeArray().forEach((obj) => {
  259. nameValueMap[obj.name] = obj.value;
  260. });
  261. $.ajax({
  262. type: 'POST',
  263. url: '/_api/pages.rename',
  264. data: $(this).serialize(),
  265. dataType: 'json'
  266. })
  267. .done(function(res) {
  268. if (!res.ok) {
  269. // if already exists
  270. $('#renamePage .msg-already-exists, #unportalize .msg-already-exists').show();
  271. $('#renamePage #linkToNewPage, #unportalize #linkToNewPage').html(`
  272. <a href="${nameValueMap.new_path}">${nameValueMap.new_path} <i class="icon-login"></i></a>
  273. `);
  274. }
  275. else {
  276. var page = res.page;
  277. top.location.href = page.path + '?renamed=' + pagePath;
  278. }
  279. });
  280. return false;
  281. });
  282. // duplicate
  283. $('#duplicatePage').on('shown.bs.modal', function(e) {
  284. $('#duplicatePage #duplicatePageName').focus();
  285. $('#duplicatePage .msg-already-exists').hide();
  286. });
  287. $('#duplicatePageForm, #unportalize-form').submit(function(e) {
  288. // create name-value map
  289. let nameValueMap = {};
  290. $(this).serializeArray().forEach((obj) => {
  291. nameValueMap[obj.name] = obj.value;
  292. });
  293. $.ajax({
  294. type: 'POST',
  295. url: '/_api/pages.duplicate',
  296. data: $(this).serialize(),
  297. dataType: 'json'
  298. }).done(function(res) {
  299. if (!res.ok) {
  300. // if already exists
  301. $('#duplicatePage .msg-already-exists').show();
  302. $('#duplicatePage #linkToNewPage').html(`
  303. <a href="${nameValueMap.new_path}">${nameValueMap.new_path} <i class="icon-login"></i></a>
  304. `);
  305. }
  306. else {
  307. var page = res.page;
  308. top.location.href = page.path + '?duplicated=' + pagePath;
  309. }
  310. });
  311. return false;
  312. });
  313. // delete
  314. $('#delete-page-form').submit(function(e) {
  315. $.ajax({
  316. type: 'POST',
  317. url: '/_api/pages.remove',
  318. data: $('#delete-page-form').serialize(),
  319. dataType: 'json'
  320. }).done(function(res) {
  321. if (!res.ok) {
  322. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  323. $('#delete-errors').addClass('alert-danger');
  324. }
  325. else {
  326. var page = res.page;
  327. top.location.href = page.path;
  328. }
  329. });
  330. return false;
  331. });
  332. $('#revert-delete-page-form').submit(function(e) {
  333. $.ajax({
  334. type: 'POST',
  335. url: '/_api/pages.revertRemove',
  336. data: $('#revert-delete-page-form').serialize(),
  337. dataType: 'json'
  338. }).done(function(res) {
  339. if (!res.ok) {
  340. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  341. $('#delete-errors').addClass('alert-danger');
  342. }
  343. else {
  344. var page = res.page;
  345. top.location.href = page.path;
  346. }
  347. });
  348. return false;
  349. });
  350. $('#unlink-page-form').submit(function(e) {
  351. $.ajax({
  352. type: 'POST',
  353. url: '/_api/pages.unlink',
  354. data: $('#unlink-page-form').serialize(),
  355. dataType: 'json'
  356. })
  357. .done(function(res) {
  358. if (!res.ok) {
  359. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  360. $('#delete-errors').addClass('alert-danger');
  361. }
  362. else {
  363. var page = res.page;
  364. top.location.href = page.path + '?unlinked=true';
  365. }
  366. });
  367. return false;
  368. });
  369. $('#create-portal-button').on('click', function(e) {
  370. $('body').addClass('on-edit');
  371. var path = $('.content-main').data('path');
  372. if (path != '/' && $('.content-main').data('page-id') == '') {
  373. var upperPage = path.substr(0, path.length - 1);
  374. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  375. if (res.ok && res.page) {
  376. $('#portal-warning-modal').modal('show');
  377. }
  378. });
  379. }
  380. });
  381. $('#portal-form-close').on('click', function(e) {
  382. $('body').removeClass('on-edit');
  383. return false;
  384. });
  385. /*
  386. * wrap short path with <strong></strong>
  387. */
  388. $('#view-list .page-list-ul-flat .page-list-link').each(function() {
  389. var $link = $(this);
  390. /* eslint-disable no-unused-vars */
  391. var text = $link.text();
  392. /* eslint-enable */
  393. var path = decodeURIComponent($link.data('path'));
  394. var shortPath = decodeURIComponent($link.data('short-path')); // convert to string
  395. if (path == null || shortPath == null) {
  396. // continue
  397. return;
  398. }
  399. path = entities.encodeHTML(path);
  400. var pattern = escapeStringRegexp(entities.encodeHTML(shortPath)) + '(/)?$';
  401. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  402. });
  403. // for list page
  404. let growiRendererForTimeline = null;
  405. $('a[data-toggle="tab"][href="#view-timeline"]').on('show.bs.tab', function() {
  406. var isShown = $('#view-timeline').data('shown');
  407. if (growiRendererForTimeline == null) {
  408. growiRendererForTimeline = new GrowiRenderer(crowi, crowiRenderer, {mode: 'timeline'});
  409. }
  410. if (isShown == 0) {
  411. $('#view-timeline .timeline-body').each(function() {
  412. var id = $(this).attr('id');
  413. var contentId = '#' + id + ' > script';
  414. var revisionBody = '#' + id + ' .revision-body';
  415. var revisionBodyElem = document.querySelector(revisionBody);
  416. /* eslint-disable no-unused-vars */
  417. var revisionPath = '#' + id + ' .revision-path';
  418. /* eslint-enable */
  419. var pagePath = document.getElementById(id).getAttribute('data-page-path');
  420. var markdown = entities.decodeHTML($(contentId).html());
  421. ReactDOM.render(<Page crowi={crowi} crowiRenderer={growiRendererForTimeline} markdown={markdown} pagePath={pagePath} />, revisionBodyElem);
  422. });
  423. $('#view-timeline').data('shown', 1);
  424. }
  425. });
  426. if (pageId) {
  427. // for Crowi Template LangProcessor
  428. $('.template-create-button', $('#revision-body')).on('click', function() {
  429. var path = $(this).data('path');
  430. var templateId = $(this).data('template');
  431. var template = $('#' + templateId).html();
  432. crowi.saveDraft(path, template);
  433. top.location.href = `${path}#edit`;
  434. });
  435. /*
  436. * transplanted to React components -- 2018.02.04 Yuki Takei
  437. *
  438. // if page exists
  439. var $rawTextOriginal = $('#raw-text-original');
  440. if ($rawTextOriginal.length > 0) {
  441. var markdown = entities.decodeHTML($('#raw-text-original').html());
  442. var dom = $('#revision-body-content').get(0);
  443. // create context object
  444. var context = {
  445. markdown,
  446. dom,
  447. currentPagePath: decodeURIComponent(location.pathname)
  448. };
  449. crowi.interceptorManager.process('preRender', context)
  450. .then(() => crowi.interceptorManager.process('prePreProcess', context))
  451. .then(() => {
  452. context.markdown = crowiRenderer.preProcess(context.markdown);
  453. })
  454. .then(() => crowi.interceptorManager.process('postPreProcess', context))
  455. .then(() => {
  456. var revisionBody = $('#revision-body-content');
  457. var parsedHTML = crowiRenderer.render(context.markdown, context.dom);
  458. context.parsedHTML = parsedHTML;
  459. Promise.resolve(context);
  460. })
  461. .then(() => crowi.interceptorManager.process('postRender', context))
  462. .then(() => crowi.interceptorManager.process('preRenderHtml', context))
  463. // render HTML with jQuery
  464. .then(() => {
  465. $('#revision-body-content').html(context.parsedHTML);
  466. $('.template-create-button').on('click', function() {
  467. var path = $(this).data('path');
  468. var templateId = $(this).data('template');
  469. var template = $('#' + templateId).html();
  470. crowi.saveDraft(path, template);
  471. top.location.href = path;
  472. });
  473. Crowi.appendEditSectionButtons('#revision-body-content', markdown);
  474. Promise.resolve($('#revision-body-content'));
  475. })
  476. // process interceptors for post rendering
  477. .then((bodyElement) => {
  478. context = Object.assign(context, {bodyElement})
  479. return crowi.interceptorManager.process('postRenderHtml', context);
  480. });
  481. }
  482. */
  483. // header affix
  484. var $affixContent = $('#page-header');
  485. if ($affixContent.length > 0) {
  486. var $affixContentContainer = $('.row.bg-title');
  487. var containerHeight = $affixContentContainer.outerHeight(true);
  488. $affixContent.affix({
  489. offset: {
  490. top: function() {
  491. return $('.navbar').outerHeight(true) + containerHeight;
  492. }
  493. }
  494. });
  495. $('[data-affix-disable]').on('click', function(e) {
  496. var $elm = $($(this).data('affix-disable'));
  497. $(window).off('.affix');
  498. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  499. return false;
  500. });
  501. }
  502. // (function () {
  503. // var timer = 0;
  504. // window.onresize = function () {
  505. // if (timer > 0) {
  506. // clearTimeout(timer);
  507. // }
  508. // timer = setTimeout(function () {
  509. // DrawScrollbar();
  510. // }, 200);
  511. // };
  512. // }());
  513. /*
  514. * transplanted to React components -- 2017.06.02 Yuki Takei
  515. *
  516. // omg
  517. function createCommentHTML(revision, creator, comment, commentedAt) {
  518. var $comment = $('<div>');
  519. var $commentImage = $('<img class="picture img-circle">')
  520. .attr('src', Crowi.userPicture(creator));
  521. var $commentCreator = $('<div class="page-comment-creator">')
  522. .text(creator.username);
  523. var $commentRevision = $('<a class="page-comment-revision label">')
  524. .attr('href', '?revision=' + revision)
  525. .text(revision.substr(0,8));
  526. if (revision !== revisionId) {
  527. $commentRevision.addClass('label-default');
  528. } else {
  529. $commentRevision.addClass('label-primary');
  530. }
  531. var $commentMeta = $('<div class="page-comment-meta">')
  532. //日付変換
  533. .text(moment(commentedAt).format('YYYY/MM/DD HH:mm:ss') + ' ')
  534. .append($commentRevision);
  535. var $commentBody = $('<div class="page-comment-body">')
  536. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  537. var $commentMain = $('<div class="page-comment-main">')
  538. .append($commentCreator)
  539. .append($commentBody)
  540. .append($commentMeta)
  541. $comment.addClass('page-comment');
  542. if (creator._id === currentUser) {
  543. $comment.addClass('page-comment-me');
  544. }
  545. if (revision !== revisionId) {
  546. $comment.addClass('page-comment-old');
  547. }
  548. $comment
  549. .append($commentImage)
  550. .append($commentMain);
  551. return $comment;
  552. }
  553. // get comments
  554. var $pageCommentList = $('.page-comments-list');
  555. var $pageCommentListNewer = $('#page-comments-list-newer');
  556. var $pageCommentListCurrent = $('#page-comments-list-current');
  557. var $pageCommentListOlder = $('#page-comments-list-older');
  558. var hasNewer = false;
  559. var hasOlder = false;
  560. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  561. if (res.ok) {
  562. var comments = res.comments;
  563. $.each(comments, function(i, comment) {
  564. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  565. if (comment.revision == revisionId) {
  566. $pageCommentListCurrent.append(commentContent);
  567. } else {
  568. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  569. $pageCommentListNewer.append(commentContent);
  570. hasNewer = true;
  571. } else {
  572. $pageCommentListOlder.append(commentContent);
  573. hasOlder = true;
  574. }
  575. }
  576. });
  577. }
  578. }).fail(function(data) {
  579. }).always(function() {
  580. if (!hasNewer) {
  581. $('.page-comments-list-toggle-newer').hide();
  582. }
  583. if (!hasOlder) {
  584. $pageCommentListOlder.addClass('collapse');
  585. $('.page-comments-list-toggle-older').hide();
  586. }
  587. });
  588. // post comment event
  589. $('#page-comment-form').on('submit', function() {
  590. var $button = $('#comment-form-button');
  591. $button.attr('disabled', 'disabled');
  592. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  593. $button.prop('disabled', false);
  594. if (data.ok) {
  595. var comment = data.comment;
  596. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  597. $('#comment-form-comment').val('');
  598. $('#comment-form-message').text('');
  599. } else {
  600. $('#comment-form-message').text(data.error);
  601. }
  602. }).fail(function(data) {
  603. if (data.status !== 200) {
  604. $('#comment-form-message').text(data.statusText);
  605. }
  606. });
  607. return false;
  608. });
  609. */
  610. // Like
  611. var $likeButton = $('.like-button');
  612. var $likeCount = $('#like-count');
  613. $likeButton.click(function() {
  614. var liked = $likeButton.data('liked');
  615. var token = $likeButton.data('csrftoken');
  616. if (!liked) {
  617. $.post('/_api/likes.add', {_csrf: token, page_id: pageId}, function(res) {
  618. if (res.ok) {
  619. MarkLiked();
  620. }
  621. });
  622. }
  623. else {
  624. $.post('/_api/likes.remove', {_csrf: token, page_id: pageId}, function(res) {
  625. if (res.ok) {
  626. MarkUnLiked();
  627. }
  628. });
  629. }
  630. return false;
  631. });
  632. var $likerList = $('#liker-list');
  633. var likers = $likerList.data('likers');
  634. if (likers && likers.length > 0) {
  635. var users = crowi.findUserByIds(likers.split(','));
  636. if (users) {
  637. AddToLikers(users);
  638. }
  639. }
  640. /* eslint-disable no-inner-declarations */
  641. function AddToLikers(users) {
  642. $.each(users, function(i, user) {
  643. $likerList.append(CreateUserLinkWithPicture(user));
  644. });
  645. }
  646. function MarkLiked() {
  647. $likeButton.addClass('active');
  648. $likeButton.data('liked', 1);
  649. $likeCount.text(parseInt($likeCount.text()) + 1);
  650. }
  651. function MarkUnLiked() {
  652. $likeButton.removeClass('active');
  653. $likeButton.data('liked', 0);
  654. $likeCount.text(parseInt($likeCount.text()) - 1);
  655. }
  656. function CreateUserLinkWithPicture(user) {
  657. var $userHtml = $('<a>');
  658. $userHtml.data('user-id', user._id);
  659. $userHtml.attr('href', '/user/' + user.username);
  660. $userHtml.attr('title', user.name);
  661. var $userPicture = $('<img class="picture picture-xs img-circle">');
  662. $userPicture.attr('alt', user.name);
  663. $userPicture.attr('src', Crowi.userPicture(user));
  664. $userHtml.append($userPicture);
  665. return $userHtml;
  666. }
  667. /* eslint-enable */
  668. if (!isSeen) {
  669. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  670. // ignore unless response has error
  671. if (res.ok && res.seenUser) {
  672. $('#content-main').data('page-is-seen', 1);
  673. }
  674. });
  675. }
  676. // presentation
  677. var presentaionInitialized = false
  678. , $b = $('body');
  679. $(document).on('click', '.toggle-presentation', function(e) {
  680. var $a = $(this);
  681. e.preventDefault();
  682. $b.toggleClass('overlay-on');
  683. if (!presentaionInitialized) {
  684. presentaionInitialized = true;
  685. $('<iframe />').attr({
  686. src: $a.attr('href')
  687. }).appendTo($('#presentation-container'));
  688. }
  689. }).on('click', '.fullscreen-layer', function() {
  690. $b.toggleClass('overlay-on');
  691. });
  692. //
  693. var me = $('body').data('me');
  694. var socket = io();
  695. socket.on('page edited', function(data) {
  696. if (data.user._id != me
  697. && data.page.path == pagePath) {
  698. $('#notifPageEdited').show();
  699. $('#notifPageEdited .edited-user').html(data.user.name);
  700. }
  701. });
  702. } // end if pageId
  703. // hash handling
  704. if (isSavedStatesOfTabChanges) {
  705. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  706. window.location.hash = '#revision-history';
  707. window.history.replaceState('', 'History', '#revision-history');
  708. });
  709. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', function() {
  710. window.location.hash = '#edit';
  711. window.history.replaceState('', 'Edit', '#edit');
  712. });
  713. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', function() {
  714. window.location.hash = '#hackmd';
  715. window.history.replaceState('', 'HackMD', '#hackmd');
  716. });
  717. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  718. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  719. window.location.hash = '#';
  720. window.history.replaceState('', '', location.href);
  721. });
  722. }
  723. else {
  724. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  725. window.history.replaceState('', 'History', '#revision-history');
  726. });
  727. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', function() {
  728. window.history.replaceState('', 'Edit', '#edit');
  729. });
  730. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', function() {
  731. window.history.replaceState('', 'HackMD', '#hackmd');
  732. });
  733. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  734. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  735. });
  736. // replace all href="#edit" link behaviors
  737. $(document).on('click', 'a[href="#edit"]', function() {
  738. window.location.replace('#edit');
  739. });
  740. }
  741. // focus to editor when 'shown.bs.tab' event fired
  742. $('a[href="#edit"]').on('shown.bs.tab', function(e) {
  743. Crowi.setCaretLineAndFocusToEditor();
  744. });
  745. });
  746. /*
  747. Crowi.getRevisionBodyContent = function() {
  748. return $('#revision-body-content').html();
  749. }
  750. Crowi.replaceRevisionBodyContent = function(html) {
  751. $('#revision-body-content').html(html);
  752. }
  753. */
  754. Crowi.findHashFromUrl = function(url) {
  755. var match;
  756. /* eslint-disable no-cond-assign */
  757. if (match = url.match(/#(.+)$/)) {
  758. return `#${match[1]}`;
  759. }
  760. /* eslint-enable */
  761. return '';
  762. };
  763. Crowi.findSectionHeader = function(hash) {
  764. if (hash.length == 0) {
  765. return;
  766. }
  767. // omit '#'
  768. const id = hash.replace('#', '');
  769. // don't use jQuery and document.querySelector
  770. // because hash may containe Base64 encoded strings
  771. const elem = document.getElementById(id);
  772. if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
  773. return elem;
  774. }
  775. return null;
  776. };
  777. Crowi.unhighlightSelectedSection = function(hash) {
  778. const elem = Crowi.findSectionHeader(hash);
  779. if (elem != null) {
  780. elem.classList.remove('highlighted');
  781. }
  782. };
  783. Crowi.highlightSelectedSection = function(hash) {
  784. const elem = Crowi.findSectionHeader(hash);
  785. if (elem != null) {
  786. elem.classList.add('highlighted');
  787. }
  788. };
  789. window.addEventListener('load', function(e) {
  790. // hash on page
  791. if (location.hash) {
  792. if (location.hash === '#edit' || location.hash === '#edit-form') {
  793. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  794. // focus
  795. Crowi.setCaretLineAndFocusToEditor();
  796. }
  797. else if (location.hash == '#hackmd') {
  798. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  799. }
  800. else if (location.hash == '#revision-history') {
  801. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  802. }
  803. }
  804. if (crowi && crowi.users || crowi.users.length == 0) {
  805. var totalUsers = crowi.users.length;
  806. var $listLiker = $('.page-list-liker');
  807. $listLiker.each(function(i, liker) {
  808. var count = $(liker).data('count') || 0;
  809. if (count/totalUsers > 0.05) {
  810. $(liker).addClass('popular-page-high');
  811. // 5%
  812. }
  813. else if (count/totalUsers > 0.02) {
  814. $(liker).addClass('popular-page-mid');
  815. // 2%
  816. }
  817. else if (count/totalUsers > 0.005) {
  818. $(liker).addClass('popular-page-low');
  819. // 0.5%
  820. }
  821. });
  822. var $listSeer = $('.page-list-seer');
  823. $listSeer.each(function(i, seer) {
  824. var count = $(seer).data('count') || 0;
  825. if (count/totalUsers > 0.10) {
  826. // 10%
  827. $(seer).addClass('popular-page-high');
  828. }
  829. else if (count/totalUsers > 0.05) {
  830. // 5%
  831. $(seer).addClass('popular-page-mid');
  832. }
  833. else if (count/totalUsers > 0.02) {
  834. // 2%
  835. $(seer).addClass('popular-page-low');
  836. }
  837. });
  838. }
  839. Crowi.highlightSelectedSection(location.hash);
  840. Crowi.modifyScrollTop();
  841. Crowi.setCaretLineAndFocusToEditor();
  842. Crowi.initSlimScrollForRevisionToc();
  843. });
  844. window.addEventListener('hashchange', function(e) {
  845. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  846. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  847. Crowi.modifyScrollTop();
  848. // hash on page
  849. if (location.hash) {
  850. if (location.hash === '#edit') {
  851. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  852. }
  853. else if (location.hash == '#hackmd') {
  854. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  855. }
  856. else if (location.hash == '#revision-history') {
  857. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  858. }
  859. }
  860. else {
  861. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  862. }
  863. });
  864. window.addEventListener('keydown', (event) => {
  865. const target = event.target;
  866. // ignore when target dom is input
  867. const inputPattern = /^input|textinput|textarea$/i;
  868. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  869. return;
  870. }
  871. switch (event.key) {
  872. case 'e':
  873. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  874. Crowi.handleKeyEHandler(event);
  875. }
  876. break;
  877. case 'c':
  878. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  879. Crowi.handleKeyCHandler(event);
  880. }
  881. break;
  882. case '/':
  883. if (event.ctrlKey || event.metaKey) {
  884. Crowi.handleKeyCtrlSlashHandler(event);
  885. }
  886. break;
  887. }
  888. });