crowi.js 30 KB

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