crowi.js 27 KB

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