crowi.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 name = $('input', this).val();
  208. if (!name.match(/^\//)) {
  209. name = '/' + name;
  210. }
  211. top.location.href = name;
  212. return false;
  213. });
  214. // rename
  215. $('#renamePage').on('shown.bs.modal', function (e) {
  216. $('#newPageName').focus();
  217. });
  218. $('#renamePageForm, #unportalize-form').submit(function(e) {
  219. $.ajax({
  220. type: 'POST',
  221. url: '/_api/pages.rename',
  222. data: $(this).serialize(),
  223. dataType: 'json'
  224. }).done(function(res) {
  225. if (!res.ok) {
  226. $('#newPageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  227. $('#newPageNameCheck').addClass('alert-danger');
  228. } else {
  229. var page = res.page;
  230. $('#newPageNameCheck').removeClass('alert-danger');
  231. $('#newPageNameCheck').html('<img src="/images/loading_s.gif"> 移動しました。移動先にジャンプします。');
  232. setTimeout(function() {
  233. top.location.href = page.path + '?renamed=' + pagePath;
  234. }, 1000);
  235. }
  236. });
  237. return false;
  238. });
  239. // delete
  240. $('#delete-page-form').submit(function(e) {
  241. $.ajax({
  242. type: 'POST',
  243. url: '/_api/pages.remove',
  244. data: $('#delete-page-form').serialize(),
  245. dataType: 'json'
  246. }).done(function(res) {
  247. if (!res.ok) {
  248. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  249. $('#delete-errors').addClass('alert-danger');
  250. } else {
  251. var page = res.page;
  252. top.location.href = page.path;
  253. }
  254. });
  255. return false;
  256. });
  257. $('#revert-delete-page-form').submit(function(e) {
  258. $.ajax({
  259. type: 'POST',
  260. url: '/_api/pages.revertRemove',
  261. data: $('#revert-delete-page-form').serialize(),
  262. dataType: 'json'
  263. }).done(function(res) {
  264. if (!res.ok) {
  265. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  266. $('#delete-errors').addClass('alert-danger');
  267. } else {
  268. var page = res.page;
  269. top.location.href = page.path;
  270. }
  271. });
  272. return false;
  273. });
  274. $('#create-portal-button').on('click', function(e) {
  275. $('.portal').removeClass('hide');
  276. $('.content-main').addClass('on-edit');
  277. $('.portal a[data-toggle="tab"][href="#edit-form"]').tab('show');
  278. var path = $('.content-main').data('path');
  279. if (path != '/' && $('.content-main').data('page-id') == '') {
  280. var upperPage = path.substr(0, path.length - 1);
  281. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  282. if (res.ok && res.page) {
  283. $('#portal-warning-modal').modal('show');
  284. }
  285. });
  286. }
  287. });
  288. $('#portal-form-close').on('click', function(e) {
  289. $('.portal').addClass('hide');
  290. $('.content-main').removeClass('on-edit');
  291. return false;
  292. });
  293. // list-link
  294. $('.page-list-link').each(function() {
  295. var $link = $(this);
  296. var text = $link.text();
  297. var path = $link.data('path');
  298. var shortPath = new String($link.data('short-path'));
  299. var escape = function(s) {
  300. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  301. };
  302. var pattern = escape(shortPath) + '(/)?$';
  303. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  304. });
  305. // for list page
  306. $('#view-timeline .timeline-body').each(function()
  307. {
  308. var id = $(this).attr('id');
  309. var contentId = '#' + id + ' > script';
  310. var revisionBody = '#' + id + ' .revision-body';
  311. var revisionPath = '#' + id + ' .revision-path';
  312. var markdown = Crowi.unescape($(contentId).html());
  313. var parsedHTML = crowiRenderer.render(markdown);
  314. $(revisionBody).html(parsedHTML);
  315. });
  316. // login
  317. $('#register').on('click', function() {
  318. $('#login-dialog').addClass('to-flip');
  319. return false;
  320. });
  321. $('#login').on('click', function() {
  322. $('#login-dialog').removeClass('to-flip');
  323. return false;
  324. });
  325. $('#btn-login-facebook').click(function(e)
  326. {
  327. var afterLogin = function(response) {
  328. if (response.status !== 'connected') {
  329. $('#login-form-errors').html('<p class="alert alert-danger">Facebookでのログインに失敗しました。</p>');
  330. } else {
  331. location.href = '/login/facebook';
  332. }
  333. };
  334. FB.getLoginStatus(function(response) {
  335. if (response.status === 'connected') {
  336. afterLogin(response);
  337. } else {
  338. FB.login(function(response) {
  339. afterLogin(response);
  340. }, {scope: 'email'});
  341. }
  342. });
  343. });
  344. $('#register-form input[name="registerForm[username]"]').change(function(e) {
  345. var username = $(this).val();
  346. $('#input-group-username').removeClass('has-error');
  347. $('#help-block-username').html("");
  348. $.getJSON('/_api/check_username', {username: username}, function(json) {
  349. if (!json.valid) {
  350. $('#help-block-username').html('<i class="fa fa-warning"></i>このユーザーIDは利用できません。<br>');
  351. $('#input-group-username').addClass('has-error');
  352. }
  353. });
  354. });
  355. $('#btn-register-facebook').click(function(e)
  356. {
  357. var afterLogin = function(response) {
  358. if (response.status !== 'connected') {
  359. $('#register-form-errors').html('<p class="alert alert-danger">Facebookでのログインに失敗しました。</p>');
  360. } else {
  361. var authR = response.authResponse;
  362. $('#register-form input[name="registerForm[fbId]"]').val(authR.userID);
  363. FB.api('/me?fields=name,username,email', function(res) {
  364. $('#register-form input[name="registerForm[name]"]').val(res.name);
  365. $('#register-form input[name="registerForm[username]"]').val(res.username || '');
  366. $('#register-form input[name="registerForm[email]"]').val(res.email);
  367. $('#register-form .facebook-info').remove();
  368. $('#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>');
  369. });
  370. }
  371. };
  372. FB.getLoginStatus(function(response) {
  373. if (response.status === 'connected') {
  374. afterLogin(response);
  375. } else {
  376. FB.login(function(response) {
  377. afterLogin(response);
  378. }, {scope: 'email'});
  379. }
  380. });
  381. });
  382. if (pageId) {
  383. // if page exists
  384. var $rawTextOriginal = $('#raw-text-original');
  385. if ($rawTextOriginal.length > 0) {
  386. var markdown = Crowi.unescape($('#raw-text-original').html());
  387. var parsedHTML = crowiRenderer.render(markdown);
  388. $('#revision-body-content').html(parsedHTML);
  389. $('.template-create-button').on('click', function() {
  390. var path = $(this).data('path');
  391. var templateId = $(this).data('template');
  392. var template = $('#' + templateId).html();
  393. crowi.saveDraft(path, template);
  394. top.location.href = path;
  395. });
  396. Crowi.correctHeaders('#revision-body-content');
  397. Crowi.revisionToc('#revision-body-content', '#revision-toc');
  398. }
  399. // header
  400. var $header = $('#page-header');
  401. if ($header.length > 0) {
  402. var headerHeight = $header.outerHeight(true);
  403. $('.header-wrap').css({height: (headerHeight + 16) + 'px'});
  404. $header.affix({
  405. offset: {
  406. top: function() {
  407. return headerHeight + 86; // (54 header + 16 header padding-top + 16 content padding-top)
  408. }
  409. }
  410. });
  411. $('[data-affix-disable]').on('click', function(e) {
  412. var $elm = $($(this).data('affix-disable'));
  413. $(window).off('.affix');
  414. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  415. return false;
  416. });
  417. }
  418. // omg
  419. function createCommentHTML(revision, creator, comment, commentedAt) {
  420. var $comment = $('<div>');
  421. var $commentImage = $('<img class="picture picture-rounded">')
  422. .attr('src', Crowi.userPicture(creator));
  423. var $commentCreator = $('<div class="page-comment-creator">')
  424. .text(creator.username);
  425. var $commentRevision = $('<a class="page-comment-revision label">')
  426. .attr('href', '?revision=' + revision)
  427. .text(revision.substr(0,8));
  428. if (revision !== revisionId) {
  429. $commentRevision.addClass('label-default');
  430. } else {
  431. $commentRevision.addClass('label-primary');
  432. }
  433. var $commentMeta = $('<div class="page-comment-meta">')
  434. .text(commentedAt + ' ')
  435. .append($commentRevision);
  436. var $commentBody = $('<div class="page-comment-body">')
  437. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  438. var $commentMain = $('<div class="page-comment-main">')
  439. .append($commentCreator)
  440. .append($commentBody)
  441. .append($commentMeta)
  442. $comment.addClass('page-comment');
  443. if (creator._id === currentUser) {
  444. $comment.addClass('page-comment-me');
  445. }
  446. if (revision !== revisionId) {
  447. $comment.addClass('page-comment-old');
  448. }
  449. $comment
  450. .append($commentImage)
  451. .append($commentMain);
  452. return $comment;
  453. }
  454. // get comments
  455. var $pageCommentList = $('.page-comments-list');
  456. var $pageCommentListNewer = $('#page-comments-list-newer');
  457. var $pageCommentListCurrent = $('#page-comments-list-current');
  458. var $pageCommentListOlder = $('#page-comments-list-older');
  459. var hasNewer = false;
  460. var hasOlder = false;
  461. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  462. if (res.ok) {
  463. var comments = res.comments;
  464. $.each(comments, function(i, comment) {
  465. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  466. if (comment.revision == revisionId) {
  467. $pageCommentListCurrent.append(commentContent);
  468. } else {
  469. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  470. $pageCommentListNewer.append(commentContent);
  471. hasNewer = true;
  472. } else {
  473. $pageCommentListOlder.append(commentContent);
  474. hasOlder = true;
  475. }
  476. }
  477. });
  478. }
  479. }).fail(function(data) {
  480. }).always(function() {
  481. if (!hasNewer) {
  482. $('.page-comments-list-toggle-newer').hide();
  483. }
  484. if (!hasOlder) {
  485. $pageCommentListOlder.addClass('collapse');
  486. $('.page-comments-list-toggle-older').hide();
  487. }
  488. });
  489. // post comment event
  490. $('#page-comment-form').on('submit', function() {
  491. var $button = $('#comment-form-button');
  492. $button.attr('disabled', 'disabled');
  493. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  494. $button.removeAttr('disabled');
  495. if (data.ok) {
  496. var comment = data.comment;
  497. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  498. $('#comment-form-comment').val('');
  499. $('#comment-form-message').text('');
  500. } else {
  501. $('#comment-form-message').text(data.error);
  502. }
  503. }).fail(function(data) {
  504. if (data.status !== 200) {
  505. $('#comment-form-message').text(data.statusText);
  506. }
  507. });
  508. return false;
  509. });
  510. // attachment
  511. var $pageAttachmentList = $('.page-attachments ul');
  512. $.get('/_api/attachment/page/' + pageId, function(res) {
  513. var attachments = res.data.attachments;
  514. if (attachments.length > 0) {
  515. $.each(attachments, function(i, file) {
  516. $pageAttachmentList.append(
  517. '<li><a href="' + file.fileUrl + '">' + (file.originalName || file.fileName) + '</a> <span class="label label-default">' + file.fileFormat + '</span></li>'
  518. );
  519. })
  520. } else {
  521. $('.page-attachments').remove();
  522. }
  523. });
  524. // bookmark
  525. var $bookmarkButton = $('#bookmark-button');
  526. $.get('/_api/bookmarks.get', {page_id: pageId}, function(res) {
  527. if (res.ok) {
  528. if (res.bookmark) {
  529. MarkBookmarked();
  530. }
  531. }
  532. });
  533. $bookmarkButton.click(function() {
  534. var bookmarked = $bookmarkButton.data('bookmarked');
  535. var token = $bookmarkButton.data('csrftoken');
  536. if (!bookmarked) {
  537. $.post('/_api/bookmarks.add', {_csrf: token, page_id: pageId}, function(res) {
  538. if (res.ok && res.bookmark) {
  539. MarkBookmarked();
  540. }
  541. });
  542. } else {
  543. $.post('/_api/bookmarks.remove', {_csrf: token, page_id: pageId}, function(res) {
  544. if (res.ok) {
  545. MarkUnBookmarked();
  546. }
  547. });
  548. }
  549. return false;
  550. });
  551. function MarkBookmarked()
  552. {
  553. $('i', $bookmarkButton)
  554. .removeClass('fa-star-o')
  555. .addClass('fa-star');
  556. $bookmarkButton.data('bookmarked', 1);
  557. }
  558. function MarkUnBookmarked()
  559. {
  560. $('i', $bookmarkButton)
  561. .removeClass('fa-star')
  562. .addClass('fa-star-o');
  563. $bookmarkButton.data('bookmarked', 0);
  564. }
  565. // Like
  566. var $likeButton = $('#like-button');
  567. var $likeCount = $('#like-count');
  568. $likeButton.click(function() {
  569. var liked = $likeButton.data('liked');
  570. var token = $likeButton.data('csrftoken');
  571. if (!liked) {
  572. $.post('/_api/likes.add', {_csrf: token, page_id: pageId}, function(res) {
  573. if (res.ok) {
  574. MarkLiked();
  575. }
  576. });
  577. } else {
  578. $.post('/_api/likes.remove', {_csrf: token, page_id: pageId}, function(res) {
  579. if (res.ok) {
  580. MarkUnLiked();
  581. }
  582. });
  583. }
  584. return false;
  585. });
  586. var $likerList = $("#liker-list");
  587. var likers = $likerList.data('likers');
  588. if (likers && likers.length > 0) {
  589. // FIXME: user data cache
  590. $.get('/_api/users.list', {user_ids: likers}, function(res) {
  591. // ignore unless response has error
  592. if (res.ok) {
  593. AddToLikers(res.users);
  594. }
  595. });
  596. }
  597. function AddToLikers (users) {
  598. $.each(users, function(i, user) {
  599. $likerList.append(CreateUserLinkWithPicture(user));
  600. });
  601. }
  602. function MarkLiked()
  603. {
  604. $likeButton.addClass('active');
  605. $likeButton.data('liked', 1);
  606. $likeCount.text(parseInt($likeCount.text()) + 1);
  607. }
  608. function MarkUnLiked()
  609. {
  610. $likeButton.removeClass('active');
  611. $likeButton.data('liked', 0);
  612. $likeCount.text(parseInt($likeCount.text()) - 1);
  613. }
  614. if (!isSeen) {
  615. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  616. // ignore unless response has error
  617. if (res.ok && res.seenUser) {
  618. $('#content-main').data('page-is-seen', 1);
  619. }
  620. });
  621. }
  622. var $seenUserList = $("#seen-user-list");
  623. if ($seenUserList && $seenUserList.length > 0) {
  624. var seenUsers = $seenUserList.data('seen-users');
  625. var seenUsersArray = seenUsers.split(',');
  626. if (seenUsers && seenUsersArray.length > 0 && seenUsersArray.length <= 10) {
  627. // FIXME: user data cache
  628. $.get('/_api/users.list', {user_ids: seenUsers}, function(res) {
  629. // ignore unless response has error
  630. if (res.ok) {
  631. AddToSeenUser(res.users);
  632. }
  633. });
  634. }
  635. }
  636. function CreateUserLinkWithPicture (user) {
  637. var $userHtml = $('<a>');
  638. $userHtml.data('user-id', user._id);
  639. $userHtml.attr('href', '/user/' + user.username);
  640. $userHtml.attr('title', user.name);
  641. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  642. $userPicture.attr('alt', user.name);
  643. $userPicture.attr('src', Crowi.userPicture(user));
  644. $userHtml.append($userPicture);
  645. return $userHtml;
  646. }
  647. function AddToSeenUser (users) {
  648. $.each(users, function(i, user) {
  649. $seenUserList.append(CreateUserLinkWithPicture(user));
  650. });
  651. }
  652. // History Diff
  653. var allRevisionIds = [];
  654. $.each($('.diff-view'), function() {
  655. allRevisionIds.push($(this).data('revisionId'));
  656. });
  657. $('.diff-view').on('click', function(e) {
  658. e.preventDefault();
  659. var getBeforeRevisionId = function(revisionId) {
  660. var currentPos = $.inArray(revisionId, allRevisionIds);
  661. if (currentPos < 0) {
  662. return false;
  663. }
  664. var beforeRevisionId = allRevisionIds[currentPos + 1];
  665. if (typeof beforeRevisionId === 'undefined') {
  666. return false;
  667. }
  668. return beforeRevisionId;
  669. };
  670. var revisionId = $(this).data('revisionId');
  671. var beforeRevisionId = getBeforeRevisionId(revisionId);
  672. var $diffDisplay = $('#diff-display-' + revisionId);
  673. var $diffIcon = $('#diff-icon-' + revisionId);
  674. if ($diffIcon.hasClass('fa-arrow-circle-right')) {
  675. $diffIcon.removeClass('fa-arrow-circle-right');
  676. $diffIcon.addClass('fa-arrow-circle-down');
  677. } else {
  678. $diffIcon.removeClass('fa-arrow-circle-down');
  679. $diffIcon.addClass('fa-arrow-circle-right');
  680. }
  681. if (beforeRevisionId === false) {
  682. $diffDisplay.text('差分はありません');
  683. $diffDisplay.slideToggle();
  684. } else {
  685. var revisionIds = revisionId + ',' + beforeRevisionId;
  686. if ($diffDisplay.data('loaded')) {
  687. $diffDisplay.slideToggle();
  688. return true;
  689. }
  690. $.ajax({
  691. type: 'GET',
  692. url: '/_api/revisions.list?revision_ids=' + revisionIds,
  693. dataType: 'json'
  694. }).done(function(res) {
  695. var currentText = res[0].body;
  696. var previousText = res[1].body;
  697. $diffDisplay.text('');
  698. var diff = jsdiff.diffLines(previousText, currentText);
  699. diff.forEach(function(part) {
  700. var color = part.added ? 'green' : part.removed ? 'red' : 'grey';
  701. var $span = $('<span>');
  702. $span.css('color', color);
  703. $span.text(part.value);
  704. $diffDisplay.append($span);
  705. });
  706. $diffDisplay.data('loaded', 1);
  707. $diffDisplay.slideToggle();
  708. });
  709. }
  710. });
  711. // default open
  712. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  713. $('.diff-view').each(function(i, diffView) {
  714. if (i < 2) {
  715. $(diffView).click();
  716. }
  717. });
  718. });
  719. // presentation
  720. var presentaionInitialized = false
  721. , $b = $('body');
  722. $(document).on('click', '.toggle-presentation', function(e) {
  723. var $a = $(this);
  724. e.preventDefault();
  725. $b.toggleClass('overlay-on');
  726. if (!presentaionInitialized) {
  727. presentaionInitialized = true;
  728. $('<iframe />').attr({
  729. src: $a.attr('href')
  730. }).appendTo($('#presentation-container'));
  731. }
  732. }).on('click', '.fullscreen-layer', function() {
  733. $b.toggleClass('overlay-on');
  734. });
  735. //
  736. var me = $('body').data('me');
  737. var socket = io();
  738. socket.on('page edited', function (data) {
  739. if (data.user._id != me
  740. && data.page.path == pagePath) {
  741. $('#notifPageEdited').show();
  742. $('#notifPageEdited .edited-user').html(data.user.name);
  743. }
  744. });
  745. } // end if pageId
  746. // hash handling
  747. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  748. window.history.pushState('', 'History', '#revision-history');
  749. });
  750. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  751. window.history.pushState('', 'Edit', '#edit-form');
  752. });
  753. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  754. window.history.pushState('', '', location.href.replace(location.hash, ''));
  755. });
  756. });
  757. Crowi.findHashFromUrl = function(url)
  758. {
  759. var match;
  760. if (match = url.match(/#(.+)$/)) {
  761. return '#' + match[1];
  762. }
  763. return "";
  764. }
  765. Crowi.unhighlightSelectedSection = function(hash)
  766. {
  767. if (!hash || hash == "" || !hash.match(/^#head.+/)) {
  768. // とりあえず head* だけ (検索結果ページで副作用出た
  769. return true;
  770. }
  771. $(hash).removeClass('highlighted');
  772. }
  773. Crowi.highlightSelectedSection = function(hash)
  774. {
  775. if (!hash || hash == "" || !hash.match(/^#head.+/)) {
  776. // とりあえず head* だけ (検索結果ページで副作用出た
  777. return true;
  778. }
  779. $(hash).addClass('highlighted');
  780. }
  781. window.addEventListener('load', function(e) {
  782. Crowi.highlightSelectedSection(location.hash);
  783. Crowi.modifyScrollTop();
  784. // hash on page
  785. if (location.hash) {
  786. if (location.hash == '#edit-form') {
  787. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  788. }
  789. if (location.hash == '#revision-history') {
  790. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  791. }
  792. }
  793. if (crowi.users || crowi.users.length == 0) {
  794. var totalUsers = crowi.users.length;
  795. var $listLiker = $('.page-list-liker');
  796. $listLiker.each(function(i, liker) {
  797. var count = $(liker).data('count') || 0;
  798. if (count/totalUsers > 0.05) {
  799. $(liker).addClass('popular-page-high');
  800. // 5%
  801. } else if (count/totalUsers > 0.02) {
  802. $(liker).addClass('popular-page-mid');
  803. // 2%
  804. } else if (count/totalUsers > 0.005) {
  805. $(liker).addClass('popular-page-low');
  806. // 0.5%
  807. }
  808. });
  809. var $listSeer = $('.page-list-seer');
  810. $listSeer.each(function(i, seer) {
  811. var count = $(seer).data('count') || 0;
  812. if (count/totalUsers > 0.10) {
  813. // 10%
  814. $(seer).addClass('popular-page-high');
  815. } else if (count/totalUsers > 0.05) {
  816. // 5%
  817. $(seer).addClass('popular-page-mid');
  818. } else if (count/totalUsers > 0.02) {
  819. // 2%
  820. $(seer).addClass('popular-page-low');
  821. }
  822. });
  823. }
  824. });
  825. window.addEventListener('hashchange', function(e) {
  826. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  827. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  828. Crowi.modifyScrollTop();
  829. // hash on page
  830. if (location.hash) {
  831. if (location.hash == '#edit-form') {
  832. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  833. }
  834. if (location.hash == '#revision-history') {
  835. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  836. }
  837. }
  838. if (location.hash == '' || location.hash.match(/^#head.+/)) {
  839. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  840. }
  841. });