crowi.js 25 KB

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