crowi.js 27 KB

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