crowi.js 24 KB

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