crowi.js 29 KB

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