crowi.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. /* jshint browser: true, jquery: true */
  2. /* Author: Sotaro KARASAWA <sotarok@crocos.co.jp>
  3. */
  4. var io = require('socket.io-client');
  5. require('bootstrap-sass');
  6. require('jquery.cookie');
  7. var Crowi = {};
  8. if (!window) {
  9. window = {};
  10. }
  11. window.Crowi = Crowi;
  12. Crowi.createErrorView = function(msg) {
  13. $('#main').prepend($('<p class="alert-message error">' + msg + '</p>'));
  14. };
  15. Crowi.correctHeaders = function(contentId) {
  16. // h1 ~ h6 の id 名を補正する
  17. var $content = $(contentId || '#revision-body-content');
  18. var i = 0;
  19. $('h1,h2,h3,h4,h5,h6', $content).each(function(idx, elm) {
  20. var id = 'head' + i++;
  21. $(this).attr('id', id);
  22. $(this).addClass('revision-head');
  23. $(this).append('<span class="revision-head-link"><a href="#' + id +'"><i class="fa fa-link"></i></a></span>');
  24. });
  25. };
  26. /**
  27. * append buttons to section headers
  28. */
  29. Crowi.appendEditSectionButtons = function(contentId, markdown) {
  30. const $content = $(contentId || '#revision-body-content');
  31. $('h1,h2,h3,h4,h5,h6', $content).each(function(idx, elm) {
  32. // get header text string
  33. const text = $(this).text();
  34. // search pos for '# ...'
  35. // https://regex101.com/r/y5rpO5/1
  36. const regexp = new RegExp(`[^\r\n]*#+[^\r\n]*${text}[^\r\n]*`);
  37. let position = markdown.search(regexp);
  38. if (position < 0) { // if not found, search with header text only
  39. position = markdown.search(text);
  40. }
  41. // add button
  42. $(this).append(`
  43. <span class="revision-head-edit-button">
  44. <a href="#edit-form" onClick="Crowi.setCaretPositionToFormBody(${position})">
  45. <i class="fa fa-edit"></i>
  46. </a>
  47. </span>
  48. `
  49. );
  50. });
  51. };
  52. /**
  53. * set 'data-caret-position' attribute that will be processed in crowi-form.js
  54. * @param {number} position
  55. */
  56. Crowi.setCaretPositionToFormBody = function(position) {
  57. const formBody = document.querySelector('#form-body');
  58. formBody.setAttribute('data-caret-position', position);
  59. }
  60. Crowi.revisionToc = function(contentId, tocId) {
  61. var $content = $(contentId || '#revision-body-content');
  62. var $tocId = $(tocId || '#revision-toc');
  63. var $tocContent = $('<div id="revision-toc-content" class="revision-toc-content collapse in"></div>');
  64. $tocId.append($tocContent);
  65. $('h1', $content).each(function(idx, elm) {
  66. var id = $(this).attr('id');
  67. var title = $(this).text();
  68. var selector = '#' + id + ' ~ h2:not(#' + id + ' ~ h1 ~ h2)';
  69. var $toc = $('<ul></ul>');
  70. var $tocLi = $('<li><a href="#' + id +'">' + title + '</a></li>');
  71. $tocContent.append($toc);
  72. $toc.append($tocLi);
  73. $(selector).each(function()
  74. {
  75. var id2 = $(this).attr('id');
  76. var title2 = $(this).text();
  77. var selector2 = '#' + id2 + ' ~ h3:not(#' + id2 + ' ~ h2 ~ h3)';
  78. var $toc2 = $('<ul></ul>');
  79. var $tocLi2 = $('<li><a href="#' + id2 +'">' + title2 + '</a></li>');
  80. $tocLi.append($toc2);
  81. $toc2.append($tocLi2);
  82. $(selector2).each(function()
  83. {
  84. var id3 = $(this).attr('id');
  85. var title3 = $(this).text();
  86. var $toc3 = $('<ul></ul>');
  87. var $tocLi3 = $('<li><a href="#' + id3 +'">' + title3 + '</a></li>');
  88. $tocLi2.append($toc3);
  89. $toc3.append($tocLi3);
  90. });
  91. });
  92. });
  93. };
  94. Crowi.escape = function(s) {
  95. s = s.replace(/&/g, '&amp;')
  96. .replace(/</g, '&lt;')
  97. .replace(/>/g, '&gt;')
  98. .replace(/'/g, '&#39;')
  99. .replace(/"/g, '&quot;')
  100. ;
  101. return s;
  102. };
  103. Crowi.unescape = function(s) {
  104. s = s.replace(/&nbsp;/g, ' ')
  105. .replace(/&amp;/g, '&')
  106. .replace(/&lt;/g, '<')
  107. .replace(/&gt;/g, '>')
  108. .replace(/&#39;/g, '\'')
  109. .replace(/&quot;/g, '"')
  110. ;
  111. return s;
  112. };
  113. // original: middleware.swigFilter
  114. Crowi.userPicture = function (user) {
  115. if (!user) {
  116. return '/images/userpicture.png';
  117. }
  118. return user.image || '/images/userpicture.png';
  119. };
  120. Crowi.modifyScrollTop = function() {
  121. var offset = 10;
  122. var hash = window.location.hash;
  123. if (hash === "") {
  124. return;
  125. }
  126. var pageHeader = document.querySelector('#page-header');
  127. if (!pageHeader) {
  128. return;
  129. }
  130. var pageHeaderRect = pageHeader.getBoundingClientRect();
  131. var sectionHeader = document.querySelector(hash);
  132. if (sectionHeader === null) {
  133. return;
  134. }
  135. var timeout = 0;
  136. if (window.scrollY === 0) {
  137. timeout = 200;
  138. }
  139. setTimeout(function() {
  140. var sectionHeaderRect = sectionHeader.getBoundingClientRect();
  141. if (sectionHeaderRect.top >= pageHeaderRect.bottom) {
  142. return;
  143. }
  144. window.scrollTo(0, (window.scrollY - pageHeaderRect.height - offset));
  145. }, timeout);
  146. }
  147. $(function() {
  148. var config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
  149. var pageId = $('#content-main').data('page-id');
  150. var revisionId = $('#content-main').data('page-revision-id');
  151. var revisionCreatedAt = $('#content-main').data('page-revision-created');
  152. var currentUser = $('#content-main').data('current-user');
  153. var isSeen = $('#content-main').data('page-is-seen');
  154. var pagePath= $('#content-main').data('path');
  155. var isEnabledLineBreaks = $('#content-main').data('linebreaks-enabled');
  156. var isSavedStatesOfTabChanges = config['isSavedStatesOfTabChanges'];
  157. // generate options obj
  158. var rendererOptions = {
  159. // see: https://www.npmjs.com/package/marked
  160. marked: {
  161. breaks: isEnabledLineBreaks
  162. }
  163. };
  164. $('[data-toggle="popover"]').popover();
  165. $('[data-toggle="tooltip"]').tooltip();
  166. $('[data-tooltip-stay]').tooltip('show');
  167. $('#toggle-sidebar').click(function(e) {
  168. var $mainContainer = $('.main-container');
  169. if ($mainContainer.hasClass('aside-hidden')) {
  170. $('.main-container').removeClass('aside-hidden');
  171. $.cookie('aside-hidden', 0, { expires: 30, path: '/' });
  172. } else {
  173. $mainContainer.addClass('aside-hidden');
  174. $.cookie('aside-hidden', 1, { expires: 30, path: '/' });
  175. }
  176. return false;
  177. });
  178. if ($.cookie('aside-hidden') == 1) {
  179. $('.main-container').addClass('aside-hidden');
  180. }
  181. $('.copy-link').on('click', function () {
  182. $(this).select();
  183. });
  184. $('#create-page').on('shown.bs.modal', function (e) {
  185. // quick hack: replace from server side rendering "date" to client side "date"
  186. var today = new Date();
  187. var month = ('0' + (today.getMonth() + 1)).slice(-2);
  188. var day = ('0' + today.getDate()).slice(-2);
  189. var dateString = today.getFullYear() + '/' + month + '/' + day;
  190. $('#create-page-today .page-today-suffix').text('/' + dateString + '/');
  191. $('#create-page-today .page-today-input2').data('prefix', '/' + dateString + '/');
  192. var input2Width = $('#create-page-today .col-xs-10').outerWidth() - 1;
  193. var newWidth = input2Width
  194. - $('#create-page-today .page-today-prefix').outerWidth()
  195. - $('#create-page-today .page-today-input1').outerWidth()
  196. - $('#create-page-today .page-today-suffix').outerWidth()
  197. - 42
  198. ;
  199. $('#create-page-today .form-control.page-today-input2').css({width: newWidth}).focus();
  200. });
  201. $('#create-page-today').submit(function(e) {
  202. var prefix1 = $('input.page-today-input1', this).data('prefix');
  203. var input1 = $('input.page-today-input1', this).val();
  204. var prefix2 = $('input.page-today-input2', this).data('prefix');
  205. var input2 = $('input.page-today-input2', this).val();
  206. if (input1 === '') {
  207. prefix1 = 'メモ';
  208. }
  209. if (input2 === '') {
  210. prefix2 = prefix2.slice(0, -1);
  211. }
  212. top.location.href = prefix1 + input1 + prefix2 + input2 + '#edit-form';
  213. return false;
  214. });
  215. $('#create-page-under-tree').submit(function(e) {
  216. var name = $('input', this).val();
  217. if (!name.match(/^\//)) {
  218. name = '/' + name;
  219. }
  220. if (name.match(/.+\/$/)) {
  221. name = name.substr(0, name.length - 1);
  222. }
  223. top.location.href = name + '#edit-form';
  224. return false;
  225. });
  226. // rename
  227. $('#renamePage').on('shown.bs.modal', function (e) {
  228. $('#newPageName').focus();
  229. });
  230. $('#renamePageForm, #unportalize-form').submit(function(e) {
  231. // create name-value map
  232. let nameValueMap = {};
  233. $(this).serializeArray().forEach((obj) => {
  234. nameValueMap[obj.name] = obj.value;
  235. })
  236. $.ajax({
  237. type: 'POST',
  238. url: '/_api/pages.rename',
  239. data: $(this).serialize(),
  240. dataType: 'json'
  241. }).done(function(res) {
  242. if (!res.ok) {
  243. // if already exists
  244. $('#newPageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  245. $('#newPageNameCheck').addClass('alert-danger');
  246. $('#linkToNewPage').html(`
  247. <i class="fa fa-fw fa-arrow-right"></i><a href="${nameValueMap.new_path}">${nameValueMap.new_path}</a>
  248. `);
  249. } else {
  250. var page = res.page;
  251. $('#newPageNameCheck').removeClass('alert-danger');
  252. //$('#newPageNameCheck').html('<img src="/images/loading_s.gif"> 移動しました。移動先にジャンプします。');
  253. // fix
  254. $('#newPageNameCheck').html('<img src="/images/loading_s.gif"> Page moved! Redirecting to new page location.');
  255. setTimeout(function() {
  256. top.location.href = page.path + '?renamed=' + pagePath;
  257. }, 1000);
  258. }
  259. });
  260. return false;
  261. });
  262. // duplicate
  263. $('#duplicatePage').on('shown.bs.modal', function (e) {
  264. $('#duplicatePageName').focus();
  265. });
  266. $('#duplicatePageForm, #unportalize-form').submit(function (e) {
  267. // create name-value map
  268. let nameValueMap = {};
  269. $(this).serializeArray().forEach((obj) => {
  270. nameValueMap[obj.name] = obj.value;
  271. })
  272. $.ajax({
  273. type: 'POST',
  274. url: '/_api/pages.duplicate',
  275. data: $(this).serialize(),
  276. dataType: 'json'
  277. }).done(function (res) {
  278. if (!res.ok) {
  279. // if already exists
  280. $('#duplicatePageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  281. $('#duplicatePageNameCheck').addClass('alert-danger');
  282. $('#linkToNewPage').html(`
  283. <i class="fa fa-fw fa-arrow-right"></i><a href="${nameValueMap.new_path}">${nameValueMap.new_path}</a>
  284. `);
  285. } else {
  286. var page = res.page;
  287. $('#duplicatePageNameCheck').removeClass('alert-danger');
  288. $('#duplicatePageNameCheck').html('<img src="/images/loading_s.gif"> Page duplicated! Redirecting to new page location.');
  289. setTimeout(function () {
  290. top.location.href = page.path + '?duplicated=' + pagePath;
  291. }, 1000);
  292. }
  293. });
  294. return false;
  295. });
  296. // delete
  297. $('#delete-page-form').submit(function(e) {
  298. $.ajax({
  299. type: 'POST',
  300. url: '/_api/pages.remove',
  301. data: $('#delete-page-form').serialize(),
  302. dataType: 'json'
  303. }).done(function(res) {
  304. if (!res.ok) {
  305. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  306. $('#delete-errors').addClass('alert-danger');
  307. } else {
  308. var page = res.page;
  309. top.location.href = page.path;
  310. }
  311. });
  312. return false;
  313. });
  314. $('#revert-delete-page-form').submit(function(e) {
  315. $.ajax({
  316. type: 'POST',
  317. url: '/_api/pages.revertRemove',
  318. data: $('#revert-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. } else {
  325. var page = res.page;
  326. top.location.href = page.path;
  327. }
  328. });
  329. return false;
  330. });
  331. $('#unlink-page-form').submit(function(e) {
  332. $.ajax({
  333. type: 'POST',
  334. url: '/_api/pages.unlink',
  335. data: $('#unlink-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. } else {
  342. var page = res.page;
  343. top.location.href = page.path + '?unlinked=true';
  344. }
  345. });
  346. return false;
  347. });
  348. $('#create-portal-button').on('click', function(e) {
  349. $('.portal').removeClass('hide');
  350. $('.content-main').addClass('on-edit');
  351. $('.portal a[data-toggle="tab"][href="#edit-form"]').tab('show');
  352. var path = $('.content-main').data('path');
  353. if (path != '/' && $('.content-main').data('page-id') == '') {
  354. var upperPage = path.substr(0, path.length - 1);
  355. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  356. if (res.ok && res.page) {
  357. $('#portal-warning-modal').modal('show');
  358. }
  359. });
  360. }
  361. });
  362. $('#portal-form-close').on('click', function(e) {
  363. $('.portal').addClass('hide');
  364. $('.content-main').removeClass('on-edit');
  365. return false;
  366. });
  367. // list-link
  368. $('.page-list-link').each(function() {
  369. var $link = $(this);
  370. var text = $link.text();
  371. var path = $link.data('path');
  372. var shortPath = new String($link.data('short-path'));
  373. var escape = function(s) {
  374. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  375. };
  376. path = Crowi.escape(path);
  377. var pattern = escape(Crowi.escape(shortPath)) + '(/)?$';
  378. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  379. });
  380. // for list page
  381. $('a[data-toggle="tab"][href="#view-timeline"]').on('show.bs.tab', function() {
  382. var isShown = $('#view-timeline').data('shown');
  383. if (isShown == 0) {
  384. $('#view-timeline .timeline-body').each(function()
  385. {
  386. var id = $(this).attr('id');
  387. var contentId = '#' + id + ' > script';
  388. var revisionBody = '#' + id + ' .revision-body';
  389. var $revisionBody = $(revisionBody);
  390. var revisionPath = '#' + id + ' .revision-path';
  391. var markdown = Crowi.unescape($(contentId).html());
  392. var parsedHTML = crowiRenderer.render(markdown, $revisionBody.get(0), rendererOptions);
  393. $revisionBody.html(parsedHTML);
  394. $('.template-create-button', revisionBody).on('click', function() {
  395. var path = $(this).data('path');
  396. var templateId = $(this).data('template');
  397. var template = $('#' + templateId).html();
  398. crowi.saveDraft(path, template);
  399. top.location.href = path;
  400. });
  401. });
  402. $('#view-timeline').data('shown', 1);
  403. }
  404. });
  405. // login
  406. $('#register').on('click', function() {
  407. $('#login-dialog').addClass('to-flip');
  408. return false;
  409. });
  410. $('#login').on('click', function() {
  411. $('#login-dialog').removeClass('to-flip');
  412. return false;
  413. });
  414. $('#register-form input[name="registerForm[username]"]').change(function(e) {
  415. var username = $(this).val();
  416. $('#input-group-username').removeClass('has-error');
  417. $('#help-block-username').html("");
  418. $.getJSON('/_api/check_username', {username: username}, function(json) {
  419. if (!json.valid) {
  420. $('#help-block-username').html('<i class="fa fa-warning"></i> This User ID is not available.<br>');
  421. $('#input-group-username').addClass('has-error');
  422. }
  423. });
  424. });
  425. if (pageId) {
  426. // if page exists
  427. var $rawTextOriginal = $('#raw-text-original');
  428. if ($rawTextOriginal.length > 0) {
  429. var markdown = Crowi.unescape($('#raw-text-original').html());
  430. var dom = $('#revision-body-content').get(0);
  431. // create context object
  432. var context = {
  433. markdown,
  434. dom,
  435. currentPagePath: decodeURIComponent(location.pathname)
  436. };
  437. crowi.interceptorManager.process('preRender', context)
  438. .then(() => crowi.interceptorManager.process('prePreProcess', context))
  439. .then(() => {
  440. context.markdown = crowiRenderer.preProcess(context.markdown, context.dom);
  441. })
  442. .then(() => crowi.interceptorManager.process('postPreProcess', context))
  443. .then(() => {
  444. var revisionBody = $('#revision-body-content');
  445. var parsedHTML = crowiRenderer.render(context.markdown, context.dom, rendererOptions);
  446. context.parsedHTML = parsedHTML;
  447. Promise.resolve(context);
  448. })
  449. .then(() => crowi.interceptorManager.process('postRender', context))
  450. .then(() => crowi.interceptorManager.process('preRenderHtml', context))
  451. // render HTML with jQuery
  452. .then(() => {
  453. $('#revision-body-content').html(context.parsedHTML);
  454. $('.template-create-button').on('click', function() {
  455. var path = $(this).data('path');
  456. var templateId = $(this).data('template');
  457. var template = $('#' + templateId).html();
  458. crowi.saveDraft(path, template);
  459. top.location.href = path;
  460. });
  461. Crowi.correctHeaders('#revision-body-content');
  462. Crowi.appendEditSectionButtons('#revision-body-content', markdown);
  463. Crowi.revisionToc('#revision-body-content', '#revision-toc');
  464. Promise.resolve($('#revision-body-content'));
  465. })
  466. // process interceptors for post rendering
  467. .then((bodyElement) => {
  468. context = Object.assign(context, {bodyElement})
  469. return crowi.interceptorManager.process('postRenderHtml', context);
  470. });
  471. }
  472. // header
  473. var $header = $('#page-header');
  474. if ($header.length > 0) {
  475. var headerHeight = $header.outerHeight(true);
  476. $('.header-wrap').css({height: (headerHeight + 16) + 'px'});
  477. $header.affix({
  478. offset: {
  479. top: function() {
  480. return headerHeight + 86; // (54 header + 16 header padding-top + 16 content padding-top)
  481. }
  482. }
  483. });
  484. $('[data-affix-disable]').on('click', function(e) {
  485. var $elm = $($(this).data('affix-disable'));
  486. $(window).off('.affix');
  487. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  488. return false;
  489. });
  490. }
  491. /*
  492. * transplanted to React components -- 2017.06.02 Yuki Takei
  493. *
  494. // omg
  495. function createCommentHTML(revision, creator, comment, commentedAt) {
  496. var $comment = $('<div>');
  497. var $commentImage = $('<img class="picture picture-rounded">')
  498. .attr('src', Crowi.userPicture(creator));
  499. var $commentCreator = $('<div class="page-comment-creator">')
  500. .text(creator.username);
  501. var $commentRevision = $('<a class="page-comment-revision label">')
  502. .attr('href', '?revision=' + revision)
  503. .text(revision.substr(0,8));
  504. if (revision !== revisionId) {
  505. $commentRevision.addClass('label-default');
  506. } else {
  507. $commentRevision.addClass('label-primary');
  508. }
  509. var $commentMeta = $('<div class="page-comment-meta">')
  510. //日付変換
  511. .text(moment(commentedAt).format('YYYY/MM/DD HH:mm:ss') + ' ')
  512. .append($commentRevision);
  513. var $commentBody = $('<div class="page-comment-body">')
  514. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  515. var $commentMain = $('<div class="page-comment-main">')
  516. .append($commentCreator)
  517. .append($commentBody)
  518. .append($commentMeta)
  519. $comment.addClass('page-comment');
  520. if (creator._id === currentUser) {
  521. $comment.addClass('page-comment-me');
  522. }
  523. if (revision !== revisionId) {
  524. $comment.addClass('page-comment-old');
  525. }
  526. $comment
  527. .append($commentImage)
  528. .append($commentMain);
  529. return $comment;
  530. }
  531. // get comments
  532. var $pageCommentList = $('.page-comments-list');
  533. var $pageCommentListNewer = $('#page-comments-list-newer');
  534. var $pageCommentListCurrent = $('#page-comments-list-current');
  535. var $pageCommentListOlder = $('#page-comments-list-older');
  536. var hasNewer = false;
  537. var hasOlder = false;
  538. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  539. if (res.ok) {
  540. var comments = res.comments;
  541. $.each(comments, function(i, comment) {
  542. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  543. if (comment.revision == revisionId) {
  544. $pageCommentListCurrent.append(commentContent);
  545. } else {
  546. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  547. $pageCommentListNewer.append(commentContent);
  548. hasNewer = true;
  549. } else {
  550. $pageCommentListOlder.append(commentContent);
  551. hasOlder = true;
  552. }
  553. }
  554. });
  555. }
  556. }).fail(function(data) {
  557. }).always(function() {
  558. if (!hasNewer) {
  559. $('.page-comments-list-toggle-newer').hide();
  560. }
  561. if (!hasOlder) {
  562. $pageCommentListOlder.addClass('collapse');
  563. $('.page-comments-list-toggle-older').hide();
  564. }
  565. });
  566. // post comment event
  567. $('#page-comment-form').on('submit', function() {
  568. var $button = $('#comment-form-button');
  569. $button.attr('disabled', 'disabled');
  570. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  571. $button.prop('disabled', false);
  572. if (data.ok) {
  573. var comment = data.comment;
  574. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  575. $('#comment-form-comment').val('');
  576. $('#comment-form-message').text('');
  577. } else {
  578. $('#comment-form-message').text(data.error);
  579. }
  580. }).fail(function(data) {
  581. if (data.status !== 200) {
  582. $('#comment-form-message').text(data.statusText);
  583. }
  584. });
  585. return false;
  586. });
  587. */
  588. // Like
  589. var $likeButton = $('.like-button');
  590. var $likeCount = $('#like-count');
  591. $likeButton.click(function() {
  592. var liked = $likeButton.data('liked');
  593. var token = $likeButton.data('csrftoken');
  594. if (!liked) {
  595. $.post('/_api/likes.add', {_csrf: token, page_id: pageId}, function(res) {
  596. if (res.ok) {
  597. MarkLiked();
  598. }
  599. });
  600. } else {
  601. $.post('/_api/likes.remove', {_csrf: token, page_id: pageId}, function(res) {
  602. if (res.ok) {
  603. MarkUnLiked();
  604. }
  605. });
  606. }
  607. return false;
  608. });
  609. var $likerList = $("#liker-list");
  610. var likers = $likerList.data('likers');
  611. if (likers && likers.length > 0) {
  612. var users = crowi.findUserByIds(likers.split(','));
  613. if (users) {
  614. AddToLikers(users);
  615. }
  616. }
  617. function AddToLikers (users) {
  618. $.each(users, function(i, user) {
  619. $likerList.append(CreateUserLinkWithPicture(user));
  620. });
  621. }
  622. function MarkLiked()
  623. {
  624. $likeButton.addClass('active');
  625. $likeButton.data('liked', 1);
  626. $likeCount.text(parseInt($likeCount.text()) + 1);
  627. }
  628. function MarkUnLiked()
  629. {
  630. $likeButton.removeClass('active');
  631. $likeButton.data('liked', 0);
  632. $likeCount.text(parseInt($likeCount.text()) - 1);
  633. }
  634. if (!isSeen) {
  635. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  636. // ignore unless response has error
  637. if (res.ok && res.seenUser) {
  638. $('#content-main').data('page-is-seen', 1);
  639. }
  640. });
  641. }
  642. function CreateUserLinkWithPicture (user) {
  643. var $userHtml = $('<a>');
  644. $userHtml.data('user-id', user._id);
  645. $userHtml.attr('href', '/user/' + user.username);
  646. $userHtml.attr('title', user.name);
  647. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  648. $userPicture.attr('alt', user.name);
  649. $userPicture.attr('src', Crowi.userPicture(user));
  650. $userHtml.append($userPicture);
  651. return $userHtml;
  652. }
  653. // presentation
  654. var presentaionInitialized = false
  655. , $b = $('body');
  656. $(document).on('click', '.toggle-presentation', function(e) {
  657. var $a = $(this);
  658. e.preventDefault();
  659. $b.toggleClass('overlay-on');
  660. if (!presentaionInitialized) {
  661. presentaionInitialized = true;
  662. $('<iframe />').attr({
  663. src: $a.attr('href')
  664. }).appendTo($('#presentation-container'));
  665. }
  666. }).on('click', '.fullscreen-layer', function() {
  667. $b.toggleClass('overlay-on');
  668. });
  669. //
  670. var me = $('body').data('me');
  671. var socket = io();
  672. socket.on('page edited', function (data) {
  673. if (data.user._id != me
  674. && data.page.path == pagePath) {
  675. $('#notifPageEdited').show();
  676. $('#notifPageEdited .edited-user').html(data.user.name);
  677. }
  678. });
  679. } // end if pageId
  680. // hash handling
  681. if (isSavedStatesOfTabChanges) {
  682. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  683. window.location.hash = '#revision-history';
  684. window.history.replaceState('', 'History', '#revision-history');
  685. });
  686. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  687. window.location.hash = '#edit-form';
  688. window.history.replaceState('', 'Edit', '#edit-form');
  689. });
  690. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  691. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  692. window.location.hash = '#';
  693. window.history.replaceState('', '', location.href);
  694. });
  695. }
  696. else {
  697. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  698. window.history.replaceState('', 'History', '#revision-history');
  699. });
  700. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  701. window.history.replaceState('', 'Edit', '#edit-form');
  702. });
  703. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  704. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  705. });
  706. // replace all href="#edit-form" link behaviors
  707. $(document).on('click', 'a[href="#edit-form"]', function() {
  708. window.location.replace('#edit-form');
  709. });
  710. }
  711. });
  712. Crowi.getRevisionBodyContent = function() {
  713. return $('#revision-body-content').html();
  714. }
  715. Crowi.replaceRevisionBodyContent = function(html) {
  716. $('#revision-body-content').html(html);
  717. }
  718. Crowi.findHashFromUrl = function(url)
  719. {
  720. var match;
  721. if (match = url.match(/#(.+)$/)) {
  722. return '#' + match[1];
  723. }
  724. return "";
  725. }
  726. Crowi.unhighlightSelectedSection = function(hash)
  727. {
  728. if (!hash || hash == "" || !hash.match(/^#head.+/)) {
  729. // とりあえず head* だけ (検索結果ページで副作用出た
  730. return true;
  731. }
  732. $(hash).removeClass('highlighted');
  733. }
  734. Crowi.highlightSelectedSection = function(hash)
  735. {
  736. if (!hash || hash == "" || !hash.match(/^#head.+/)) {
  737. // とりあえず head* だけ (検索結果ページで副作用出た
  738. return true;
  739. }
  740. $(hash).addClass('highlighted');
  741. }
  742. window.addEventListener('load', function(e) {
  743. // hash on page
  744. if (location.hash) {
  745. if (location.hash == '#edit-form') {
  746. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  747. }
  748. if (location.hash == '#revision-history') {
  749. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  750. }
  751. }
  752. if (crowi && crowi.users || crowi.users.length == 0) {
  753. var totalUsers = crowi.users.length;
  754. var $listLiker = $('.page-list-liker');
  755. $listLiker.each(function(i, liker) {
  756. var count = $(liker).data('count') || 0;
  757. if (count/totalUsers > 0.05) {
  758. $(liker).addClass('popular-page-high');
  759. // 5%
  760. } else if (count/totalUsers > 0.02) {
  761. $(liker).addClass('popular-page-mid');
  762. // 2%
  763. } else if (count/totalUsers > 0.005) {
  764. $(liker).addClass('popular-page-low');
  765. // 0.5%
  766. }
  767. });
  768. var $listSeer = $('.page-list-seer');
  769. $listSeer.each(function(i, seer) {
  770. var count = $(seer).data('count') || 0;
  771. if (count/totalUsers > 0.10) {
  772. // 10%
  773. $(seer).addClass('popular-page-high');
  774. } else if (count/totalUsers > 0.05) {
  775. // 5%
  776. $(seer).addClass('popular-page-mid');
  777. } else if (count/totalUsers > 0.02) {
  778. // 2%
  779. $(seer).addClass('popular-page-low');
  780. }
  781. });
  782. }
  783. Crowi.highlightSelectedSection(location.hash);
  784. Crowi.modifyScrollTop();
  785. });
  786. window.addEventListener('hashchange', function(e) {
  787. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  788. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  789. Crowi.modifyScrollTop();
  790. // hash on page
  791. if (location.hash) {
  792. if (location.hash == '#edit-form') {
  793. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  794. }
  795. if (location.hash == '#revision-history') {
  796. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  797. }
  798. }
  799. if (location.hash == '' || location.hash.match(/^#head.+/)) {
  800. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  801. }
  802. });