crowi.js 28 KB

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