crowi.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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('bootstrap-sass');
  15. require('jquery.cookie');
  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-form" 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-form"]').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-form';
  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-form';
  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-form`;
  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-form"]').on('show.bs.tab', function() {
  710. window.location.hash = '#edit-form';
  711. window.history.replaceState('', 'Edit', '#edit-form');
  712. });
  713. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  714. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  715. window.location.hash = '#';
  716. window.history.replaceState('', '', location.href);
  717. });
  718. }
  719. else {
  720. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  721. window.history.replaceState('', 'History', '#revision-history');
  722. });
  723. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  724. window.history.replaceState('', 'Edit', '#edit-form');
  725. });
  726. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  727. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  728. });
  729. // replace all href="#edit-form" link behaviors
  730. $(document).on('click', 'a[href="#edit-form"]', function() {
  731. window.location.replace('#edit-form');
  732. });
  733. }
  734. // focus to editor when 'shown.bs.tab' event fired
  735. $('a[href="#edit-form"]').on('shown.bs.tab', function(e) {
  736. Crowi.setCaretLineAndFocusToEditor();
  737. });
  738. });
  739. /*
  740. Crowi.getRevisionBodyContent = function() {
  741. return $('#revision-body-content').html();
  742. }
  743. Crowi.replaceRevisionBodyContent = function(html) {
  744. $('#revision-body-content').html(html);
  745. }
  746. */
  747. Crowi.findHashFromUrl = function(url) {
  748. var match;
  749. /* eslint-disable no-cond-assign */
  750. if (match = url.match(/#(.+)$/)) {
  751. return `#${match[1]}`;
  752. }
  753. /* eslint-enable */
  754. return '';
  755. };
  756. Crowi.findSectionHeader = function(hash) {
  757. if (hash.length == 0) {
  758. return;
  759. }
  760. // omit '#'
  761. const id = hash.replace('#', '');
  762. // don't use jQuery and document.querySelector
  763. // because hash may containe Base64 encoded strings
  764. const elem = document.getElementById(id);
  765. if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
  766. return elem;
  767. }
  768. return null;
  769. };
  770. Crowi.unhighlightSelectedSection = function(hash) {
  771. const elem = Crowi.findSectionHeader(hash);
  772. if (elem != null) {
  773. elem.classList.remove('highlighted');
  774. }
  775. };
  776. Crowi.highlightSelectedSection = function(hash) {
  777. const elem = Crowi.findSectionHeader(hash);
  778. if (elem != null) {
  779. elem.classList.add('highlighted');
  780. }
  781. };
  782. window.addEventListener('load', function(e) {
  783. // hash on page
  784. if (location.hash) {
  785. if (location.hash == '#edit-form') {
  786. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  787. // focus
  788. Crowi.setCaretLineAndFocusToEditor();
  789. }
  790. if (location.hash == '#revision-history') {
  791. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  792. }
  793. }
  794. if (crowi && crowi.users || crowi.users.length == 0) {
  795. var totalUsers = crowi.users.length;
  796. var $listLiker = $('.page-list-liker');
  797. $listLiker.each(function(i, liker) {
  798. var count = $(liker).data('count') || 0;
  799. if (count/totalUsers > 0.05) {
  800. $(liker).addClass('popular-page-high');
  801. // 5%
  802. }
  803. else if (count/totalUsers > 0.02) {
  804. $(liker).addClass('popular-page-mid');
  805. // 2%
  806. }
  807. else if (count/totalUsers > 0.005) {
  808. $(liker).addClass('popular-page-low');
  809. // 0.5%
  810. }
  811. });
  812. var $listSeer = $('.page-list-seer');
  813. $listSeer.each(function(i, seer) {
  814. var count = $(seer).data('count') || 0;
  815. if (count/totalUsers > 0.10) {
  816. // 10%
  817. $(seer).addClass('popular-page-high');
  818. }
  819. else if (count/totalUsers > 0.05) {
  820. // 5%
  821. $(seer).addClass('popular-page-mid');
  822. }
  823. else if (count/totalUsers > 0.02) {
  824. // 2%
  825. $(seer).addClass('popular-page-low');
  826. }
  827. });
  828. }
  829. Crowi.highlightSelectedSection(location.hash);
  830. Crowi.modifyScrollTop();
  831. Crowi.setCaretLineAndFocusToEditor();
  832. Crowi.initSlimScrollForRevisionToc();
  833. });
  834. window.addEventListener('hashchange', function(e) {
  835. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  836. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  837. Crowi.modifyScrollTop();
  838. // hash on page
  839. if (location.hash) {
  840. if (location.hash == '#edit-form') {
  841. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  842. }
  843. if (location.hash == '#revision-history') {
  844. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  845. }
  846. }
  847. else {
  848. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  849. }
  850. });
  851. window.addEventListener('keydown', (event) => {
  852. const target = event.target;
  853. // ignore when target dom is input
  854. const inputPattern = /^input|textinput|textarea$/i;
  855. if (target.tagName.match(inputPattern) || target.isContentEditable) {
  856. return;
  857. }
  858. switch (event.key) {
  859. case 'e':
  860. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  861. Crowi.handleKeyEHandler(event);
  862. }
  863. break;
  864. case 'c':
  865. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  866. Crowi.handleKeyCHandler(event);
  867. }
  868. break;
  869. case '/':
  870. if (event.ctrlKey || event.metaKey) {
  871. Crowi.handleKeyCtrlSlashHandler(event);
  872. }
  873. break;
  874. }
  875. });