crowi.js 28 KB

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