crowi.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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 = new String($link.data('short-path'));
  306. var escape = function(s) {
  307. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  308. };
  309. var pattern = escape(shortPath) + '(/)?$';
  310. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  311. });
  312. // for list page
  313. $('#view-timeline .timeline-body').each(function()
  314. {
  315. var id = $(this).attr('id');
  316. var contentId = '#' + id + ' > script';
  317. var revisionBody = '#' + id + ' .revision-body';
  318. var revisionPath = '#' + id + ' .revision-path';
  319. var renderer = new Crowi.renderer($(contentId).html(), $(revisionBody));
  320. renderer.render();
  321. });
  322. // login
  323. $('#register').on('click', function() {
  324. $('#login-dialog').addClass('to-flip');
  325. return false;
  326. });
  327. $('#login').on('click', function() {
  328. $('#login-dialog').removeClass('to-flip');
  329. return false;
  330. });
  331. $('#btn-login-facebook').click(function(e)
  332. {
  333. var afterLogin = function(response) {
  334. if (response.status !== 'connected') {
  335. $('#login-form-errors').html('<p class="alert alert-danger">Facebookでのログインに失敗しました。</p>');
  336. } else {
  337. location.href = '/login/facebook';
  338. }
  339. };
  340. FB.getLoginStatus(function(response) {
  341. if (response.status === 'connected') {
  342. afterLogin(response);
  343. } else {
  344. FB.login(function(response) {
  345. afterLogin(response);
  346. }, {scope: 'email'});
  347. }
  348. });
  349. });
  350. $('#register-form input[name="registerForm[username]"]').change(function(e) {
  351. var username = $(this).val();
  352. $('#input-group-username').removeClass('has-error');
  353. $('#help-block-username').html("");
  354. $.getJSON('/_api/check_username', {username: username}, function(json) {
  355. if (!json.valid) {
  356. $('#help-block-username').html('<i class="fa fa-warning"></i>このユーザーIDは利用できません。<br>');
  357. $('#input-group-username').addClass('has-error');
  358. }
  359. });
  360. });
  361. $('#btn-register-facebook').click(function(e)
  362. {
  363. var afterLogin = function(response) {
  364. if (response.status !== 'connected') {
  365. $('#register-form-errors').html('<p class="alert alert-danger">Facebookでのログインに失敗しました。</p>');
  366. } else {
  367. var authR = response.authResponse;
  368. $('#register-form input[name="registerForm[fbId]"]').val(authR.userID);
  369. FB.api('/me?fields=name,username,email', function(res) {
  370. $('#register-form input[name="registerForm[name]"]').val(res.name);
  371. $('#register-form input[name="registerForm[username]"]').val(res.username || '');
  372. $('#register-form input[name="registerForm[email]"]').val(res.email);
  373. $('#register-form .facebook-info').remove();
  374. $('#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>');
  375. });
  376. }
  377. };
  378. FB.getLoginStatus(function(response) {
  379. if (response.status === 'connected') {
  380. afterLogin(response);
  381. } else {
  382. FB.login(function(response) {
  383. afterLogin(response);
  384. }, {scope: 'email'});
  385. }
  386. });
  387. });
  388. if (pageId) {
  389. // if page exists
  390. var $rawTextOriginal = $('#raw-text-original');
  391. if ($rawTextOriginal.length > 0) {
  392. var renderer = new Crowi.renderer($('#raw-text-original').html());
  393. renderer.render();
  394. Crowi.correctHeaders('#revision-body-content');
  395. Crowi.revisionToc('#revision-body-content', '#revision-toc');
  396. }
  397. // header
  398. var $header = $('#page-header');
  399. if ($header.length > 0) {
  400. var headerHeight = $header.outerHeight(true);
  401. $('.header-wrap').css({height: (headerHeight + 16) + 'px'});
  402. $header.affix({
  403. offset: {
  404. top: function() {
  405. return headerHeight + 86; // (54 header + 16 header padding-top + 16 content padding-top)
  406. }
  407. }
  408. });
  409. $('[data-affix-disable]').on('click', function(e) {
  410. var $elm = $($(this).data('affix-disable'));
  411. $(window).off('.affix');
  412. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  413. return false;
  414. });
  415. }
  416. // omg
  417. function createCommentHTML(revision, creator, comment, commentedAt) {
  418. var $comment = $('<div>');
  419. var $commentImage = $('<img class="picture picture-rounded">')
  420. .attr('src', Crowi.userPicture(creator));
  421. var $commentCreator = $('<div class="page-comment-creator">')
  422. .text(creator.username);
  423. var $commentRevision = $('<a class="page-comment-revision label">')
  424. .attr('href', '?revision=' + revision)
  425. .text(revision.substr(0,8));
  426. if (revision !== revisionId) {
  427. $commentRevision.addClass('label-default');
  428. } else {
  429. $commentRevision.addClass('label-primary');
  430. }
  431. var $commentMeta = $('<div class="page-comment-meta">')
  432. .text(commentedAt + ' ')
  433. .append($commentRevision);
  434. var $commentBody = $('<div class="page-comment-body">')
  435. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  436. var $commentMain = $('<div class="page-comment-main">')
  437. .append($commentCreator)
  438. .append($commentBody)
  439. .append($commentMeta)
  440. $comment.addClass('page-comment');
  441. if (creator._id === currentUser) {
  442. $comment.addClass('page-comment-me');
  443. }
  444. if (revision !== revisionId) {
  445. $comment.addClass('page-comment-old');
  446. }
  447. $comment
  448. .append($commentImage)
  449. .append($commentMain);
  450. return $comment;
  451. }
  452. // get comments
  453. var $pageCommentList = $('.page-comments-list');
  454. var $pageCommentListNewer = $('#page-comments-list-newer');
  455. var $pageCommentListCurrent = $('#page-comments-list-current');
  456. var $pageCommentListOlder = $('#page-comments-list-older');
  457. var hasNewer = false;
  458. var hasOlder = false;
  459. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  460. if (res.ok) {
  461. var comments = res.comments;
  462. $.each(comments, function(i, comment) {
  463. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  464. if (comment.revision == revisionId) {
  465. $pageCommentListCurrent.append(commentContent);
  466. } else {
  467. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  468. $pageCommentListNewer.append(commentContent);
  469. hasNewer = true;
  470. } else {
  471. $pageCommentListOlder.append(commentContent);
  472. hasOlder = true;
  473. }
  474. }
  475. });
  476. }
  477. }).fail(function(data) {
  478. }).always(function() {
  479. if (!hasNewer) {
  480. $('.page-comments-list-toggle-newer').hide();
  481. }
  482. if (!hasOlder) {
  483. $pageCommentListOlder.addClass('collapse');
  484. $('.page-comments-list-toggle-older').hide();
  485. }
  486. });
  487. // post comment event
  488. $('#page-comment-form').on('submit', function() {
  489. var $button = $('#comment-form-button');
  490. $button.attr('disabled', 'disabled');
  491. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  492. $button.removeAttr('disabled');
  493. if (data.ok) {
  494. var comment = data.comment;
  495. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  496. $('#comment-form-comment').val('');
  497. $('#comment-form-message').text('');
  498. } else {
  499. $('#comment-form-message').text(data.error);
  500. }
  501. }).fail(function(data) {
  502. if (data.status !== 200) {
  503. $('#comment-form-message').text(data.statusText);
  504. }
  505. });
  506. return false;
  507. });
  508. // attachment
  509. var $pageAttachmentList = $('.page-attachments ul');
  510. $.get('/_api/attachment/page/' + pageId, function(res) {
  511. var attachments = res.data.attachments;
  512. if (attachments.length > 0) {
  513. $.each(attachments, function(i, file) {
  514. $pageAttachmentList.append(
  515. '<li><a href="' + file.fileUrl + '">' + (file.originalName || file.fileName) + '</a> <span class="label label-default">' + file.fileFormat + '</span></li>'
  516. );
  517. })
  518. } else {
  519. $('.page-attachments').remove();
  520. }
  521. });
  522. // bookmark
  523. var $bookmarkButton = $('#bookmark-button');
  524. $.get('/_api/bookmarks.get', {page_id: pageId}, function(res) {
  525. if (res.ok) {
  526. if (res.bookmark) {
  527. MarkBookmarked();
  528. }
  529. }
  530. });
  531. $bookmarkButton.click(function() {
  532. var bookmarked = $bookmarkButton.data('bookmarked');
  533. if (!bookmarked) {
  534. $.post('/_api/bookmarks.add', {page_id: pageId}, function(res) {
  535. if (res.ok && res.bookmark) {
  536. MarkBookmarked();
  537. }
  538. });
  539. } else {
  540. $.post('/_api/bookmarks.remove', {page_id: pageId}, function(res) {
  541. if (res.ok) {
  542. MarkUnBookmarked();
  543. }
  544. });
  545. }
  546. return false;
  547. });
  548. function MarkBookmarked()
  549. {
  550. $('i', $bookmarkButton)
  551. .removeClass('fa-star-o')
  552. .addClass('fa-star');
  553. $bookmarkButton.data('bookmarked', 1);
  554. }
  555. function MarkUnBookmarked()
  556. {
  557. $('i', $bookmarkButton)
  558. .removeClass('fa-star')
  559. .addClass('fa-star-o');
  560. $bookmarkButton.data('bookmarked', 0);
  561. }
  562. // Like
  563. var $likeButton = $('#like-button');
  564. var $likeCount = $('#like-count');
  565. $likeButton.click(function() {
  566. var liked = $likeButton.data('liked');
  567. if (!liked) {
  568. $.post('/_api/likes.add', {page_id: pageId}, function(res) {
  569. if (res.ok) {
  570. MarkLiked();
  571. }
  572. });
  573. } else {
  574. $.post('/_api/likes.remove', {page_id: pageId}, function(res) {
  575. if (res.ok) {
  576. MarkUnLiked();
  577. }
  578. });
  579. }
  580. return false;
  581. });
  582. var $likerList = $("#liker-list");
  583. var likers = $likerList.data('likers');
  584. if (likers && likers.length > 0) {
  585. // FIXME: user data cache
  586. $.get('/_api/users.list', {user_ids: likers}, function(res) {
  587. // ignore unless response has error
  588. if (res.ok) {
  589. AddToLikers(res.users);
  590. }
  591. });
  592. }
  593. function AddToLikers (users) {
  594. $.each(users, function(i, user) {
  595. $likerList.append(CreateUserLinkWithPicture(user));
  596. });
  597. }
  598. function MarkLiked()
  599. {
  600. $likeButton.addClass('active');
  601. $likeButton.data('liked', 1);
  602. $likeCount.text(parseInt($likeCount.text()) + 1);
  603. }
  604. function MarkUnLiked()
  605. {
  606. $likeButton.removeClass('active');
  607. $likeButton.data('liked', 0);
  608. $likeCount.text(parseInt($likeCount.text()) - 1);
  609. }
  610. if (!isSeen) {
  611. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  612. // ignore unless response has error
  613. if (res.ok && res.seenUser) {
  614. $('#content-main').data('page-is-seen', 1);
  615. }
  616. });
  617. }
  618. var $seenUserList = $("#seen-user-list");
  619. var seenUsers = $seenUserList.data('seen-users');
  620. var seenUsersArray = seenUsers.split(',');
  621. if (seenUsers && seenUsersArray.length > 0 && seenUsersArray.length <= 10) {
  622. // FIXME: user data cache
  623. $.get('/_api/users.list', {user_ids: seenUsers}, function(res) {
  624. // ignore unless response has error
  625. if (res.ok) {
  626. AddToSeenUser(res.users);
  627. }
  628. });
  629. }
  630. function CreateUserLinkWithPicture (user) {
  631. var $userHtml = $('<a>');
  632. $userHtml.data('user-id', user._id);
  633. $userHtml.attr('href', '/user/' + user.username);
  634. $userHtml.attr('title', user.name);
  635. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  636. $userPicture.attr('alt', user.name);
  637. $userPicture.attr('src', Crowi.userPicture(user));
  638. $userHtml.append($userPicture);
  639. return $userHtml;
  640. }
  641. function AddToSeenUser (users) {
  642. $.each(users, function(i, user) {
  643. $seenUserList.append(CreateUserLinkWithPicture(user));
  644. });
  645. }
  646. // History Diff
  647. var allRevisionIds = [];
  648. $.each($('.diff-view'), function() {
  649. allRevisionIds.push($(this).data('revisionId'));
  650. });
  651. $('.diff-view').on('click', function(e) {
  652. e.preventDefault();
  653. var getBeforeRevisionId = function(revisionId) {
  654. var currentPos = $.inArray(revisionId, allRevisionIds);
  655. if (currentPos < 0) {
  656. return false;
  657. }
  658. var beforeRevisionId = allRevisionIds[currentPos + 1];
  659. if (typeof beforeRevisionId === 'undefined') {
  660. return false;
  661. }
  662. return beforeRevisionId;
  663. };
  664. var revisionId = $(this).data('revisionId');
  665. var beforeRevisionId = getBeforeRevisionId(revisionId);
  666. var $diffDisplay = $('#diff-display-' + revisionId);
  667. var $diffIcon = $('#diff-icon-' + revisionId);
  668. if ($diffIcon.hasClass('fa-arrow-circle-right')) {
  669. $diffIcon.removeClass('fa-arrow-circle-right');
  670. $diffIcon.addClass('fa-arrow-circle-down');
  671. } else {
  672. $diffIcon.removeClass('fa-arrow-circle-down');
  673. $diffIcon.addClass('fa-arrow-circle-right');
  674. }
  675. if (beforeRevisionId === false) {
  676. $diffDisplay.text('差分はありません');
  677. $diffDisplay.slideToggle();
  678. } else {
  679. var revisionIds = revisionId + ',' + beforeRevisionId;
  680. $.ajax({
  681. type: 'GET',
  682. url: '/_api/revisions.list?revision_ids=' + revisionIds,
  683. dataType: 'json'
  684. }).done(function(res) {
  685. var currentText = res[0].body;
  686. var previousText = res[1].body;
  687. $diffDisplay.text('');
  688. var diff = jsdiff.diffLines(previousText, currentText);
  689. diff.forEach(function(part) {
  690. var color = part.added ? 'green' : part.removed ? 'red' : 'grey';
  691. var $span = $('<span>');
  692. $span.css('color', color);
  693. $span.text(part.value);
  694. $diffDisplay.append($span);
  695. });
  696. $diffDisplay.slideToggle();
  697. });
  698. }
  699. });
  700. // default open
  701. $('.diff-view').each(function(i, diffView) {
  702. if (i < 2) {
  703. $(diffView).click();
  704. }
  705. });
  706. // presentation
  707. var presentaionInitialized = false
  708. , $b = $('body');
  709. $(document).on('click', '.toggle-presentation', function(e) {
  710. var $a = $(this);
  711. e.preventDefault();
  712. $b.toggleClass('overlay-on');
  713. if (!presentaionInitialized) {
  714. presentaionInitialized = true;
  715. $('<iframe />').attr({
  716. src: $a.attr('href')
  717. }).appendTo($('#presentation-container'));
  718. }
  719. }).on('click', '.fullscreen-layer', function() {
  720. $b.toggleClass('overlay-on');
  721. });
  722. //
  723. var me = $('body').data('me');
  724. var socket = io();
  725. socket.on('page edited', function (data) {
  726. if (data.user._id != me
  727. && data.page.path == pagePath) {
  728. $('#notifPageEdited').show();
  729. $('#notifPageEdited .edited-user').html(data.user.name);
  730. }
  731. });
  732. } // end if pageId
  733. // for search
  734. //
  735. });