crowi.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /* jshint browser: true, jquery: true */
  2. /* global FB, marked */
  3. /* Author: Sotaro KARASAWA <sotarok@crocos.co.jp>
  4. */
  5. var hljs = require('highlight.js');
  6. var marked = require('marked');
  7. var Crowi = {};
  8. if (!window) {
  9. window = {};
  10. }
  11. window.Crowi = Crowi;
  12. Crowi.createErrorView = function(msg) {
  13. $('#main').prepend($('<p class="alert-message error">' + msg + '</p>'));
  14. };
  15. Crowi.linkPath = function(revisionPath) {
  16. var $revisionPath = revisionPath || '#revision-path';
  17. var $title = $($revisionPath);
  18. var pathData = $('#content-main').data('path');
  19. if (!pathData) {
  20. return ;
  21. }
  22. var realPath = pathData.trim();
  23. if (realPath.substr(-1, 1) == '/') {
  24. realPath = realPath.substr(0, realPath.length - 1);
  25. }
  26. var path = '';
  27. var pathHtml = '';
  28. var splittedPath = realPath.split(/\//);
  29. splittedPath.shift();
  30. splittedPath.forEach(function(sub) {
  31. path += '/';
  32. pathHtml += ' <a href="' + path + '">/</a> ';
  33. if (sub) {
  34. path += sub;
  35. pathHtml += '<a href="' + path + '">' + sub + '</a>';
  36. }
  37. });
  38. if (path.substr(-1, 1) != '/') {
  39. path += '/';
  40. pathHtml += ' <a href="' + path + '" class="last-path">/</a>';
  41. }
  42. $title.html(pathHtml);
  43. };
  44. Crowi.correctHeaders = function(contentId) {
  45. // h1 ~ h6 の id 名を補正する
  46. var $content = $(contentId || '#revision-body-content');
  47. var i = 0;
  48. $('h1,h2,h3,h4,h5,h6', $content).each(function(idx, elm) {
  49. var id = 'head' + i++;
  50. $(this).attr('id', id);
  51. $(this).addClass('revision-head');
  52. $(this).append('<span class="revision-head-link"><a href="#' + id +'"><i class="fa fa-link"></i></a></span>');
  53. });
  54. };
  55. Crowi.revisionToc = function(contentId, tocId) {
  56. var $content = $(contentId || '#revision-body-content');
  57. var $tocId = $(tocId || '#revision-toc');
  58. var $tocContent = $('<div id="revision-toc-content" class="revision-toc-content collapse"></div>');
  59. $tocId.append($tocContent);
  60. $('h1', $content).each(function(idx, elm) {
  61. var id = $(this).attr('id');
  62. var title = $(this).text();
  63. var selector = '#' + id + ' ~ h2:not(#' + id + ' ~ h1 ~ h2)';
  64. var $toc = $('<ul></ul>');
  65. var $tocLi = $('<li><a href="#' + id +'">' + title + '</a></li>');
  66. $tocContent.append($toc);
  67. $toc.append($tocLi);
  68. $(selector).each(function()
  69. {
  70. var id2 = $(this).attr('id');
  71. var title2 = $(this).text();
  72. var selector2 = '#' + id2 + ' ~ h3:not(#' + id2 + ' ~ h2 ~ h3)';
  73. var $toc2 = $('<ul></ul>');
  74. var $tocLi2 = $('<li><a href="#' + id2 +'">' + title2 + '</a></li>');
  75. $tocLi.append($toc2);
  76. $toc2.append($tocLi2);
  77. $(selector2).each(function()
  78. {
  79. var id3 = $(this).attr('id');
  80. var title3 = $(this).text();
  81. var $toc3 = $('<ul></ul>');
  82. var $tocLi3 = $('<li><a href="#' + id3 +'">' + title3 + '</a></li>');
  83. $tocLi2.append($toc3);
  84. $toc3.append($tocLi3);
  85. });
  86. });
  87. });
  88. };
  89. Crowi.escape = function(s) {
  90. s = s.replace(/&/g, '&amp;')
  91. .replace(/</g, '&lt;')
  92. .replace(/>/g, '&gt;')
  93. .replace(/'/g, '&#39;')
  94. .replace(/"/g, '&quot;')
  95. ;
  96. return s;
  97. };
  98. Crowi.unescape = function(s) {
  99. s = s.replace(/&nbsp;/g, ' ')
  100. .replace(/&amp;/g, '&')
  101. .replace(/&lt;/g, '<')
  102. .replace(/&gt;/g, '>')
  103. .replace(/&#39;/g, '\'')
  104. .replace(/&quot;/g, '"')
  105. ;
  106. return s;
  107. };
  108. Crowi.getRendererType = function() {
  109. return new Crowi.rendererType.markdown();
  110. };
  111. Crowi.rendererType = {};
  112. Crowi.rendererType.markdown = function(){};
  113. Crowi.rendererType.markdown.prototype = {
  114. render: function(contentText) {
  115. marked.setOptions({
  116. gfm: true,
  117. highlight: function (code, lang, callback) {
  118. var result, hl;
  119. if (lang) {
  120. try {
  121. hl = hljs.highlight(lang, code);
  122. result = hl.value;
  123. } catch (e) {
  124. result = code;
  125. }
  126. } else {
  127. //result = hljs.highlightAuto(code);
  128. //callback(null, result.value);
  129. result = code;
  130. }
  131. return callback(null, result);
  132. },
  133. tables: true,
  134. breaks: true,
  135. pedantic: false,
  136. sanitize: false,
  137. smartLists: true,
  138. smartypants: false,
  139. langPrefix: 'lang-'
  140. });
  141. var contentHtml = Crowi.unescape(contentText);
  142. contentHtml = this.expandImage(contentHtml);
  143. contentHtml = this.link(contentHtml);
  144. var $body = this.$revisionBody;
  145. // Using async version of marked
  146. marked(contentHtml, {}, function (err, content) {
  147. if (err) {
  148. throw err;
  149. }
  150. $body.html(content);
  151. });
  152. },
  153. link: function (content) {
  154. return content
  155. //.replace(/\s(https?:\/\/[\S]+)/g, ' <a href="$1">$1</a>') // リンク
  156. .replace(/\s<((\/[^>]+?){2,})>/g, ' <a href="$1">$1</a>') // ページ間リンク: <> でかこまれてて / から始まり、 / が2個以上
  157. ;
  158. },
  159. expandImage: function (content) {
  160. return content.replace(/\s(https?:\/\/[\S]+\.(jpg|jpeg|gif|png))/g, ' <a href="$1"><img src="$1" class="auto-expanded-image"></a>');
  161. }
  162. };
  163. Crowi.renderer = function (contentText, revisionBody) {
  164. var $revisionBody = revisionBody || $('#revision-body-content');
  165. this.contentText = contentText;
  166. this.$revisionBody = $revisionBody;
  167. this.format = 'markdown'; // とりあえず
  168. this.renderer = Crowi.getRendererType();
  169. this.renderer.$revisionBody = this.$revisionBody;
  170. };
  171. Crowi.renderer.prototype = {
  172. render: function() {
  173. this.renderer.render(this.contentText);
  174. }
  175. };
  176. // original: middleware.swigFilter
  177. Crowi.userPicture = function (user) {
  178. if (!user) {
  179. return '/images/userpicture.png';
  180. }
  181. if (user.image && user.image != '/images/userpicture.png') {
  182. return user.image;
  183. } else if (user.fbId) {
  184. return '//graph.facebook.com/' + user.fbId + '/picture?size=square';
  185. } else {
  186. return '/images/userpicture.png';
  187. }
  188. };
  189. $(function() {
  190. var pageId = $('#content-main').data('page-id');
  191. var revisionId = $('#content-main').data('page-revision-id');
  192. var revisionCreatedAt = $('#content-main').data('page-revision-created');
  193. var currentUser = $('#content-main').data('current-user');
  194. var isSeen = $('#content-main').data('page-is-seen');
  195. Crowi.linkPath();
  196. $('[data-toggle="tooltip"]').tooltip();
  197. $('[data-tooltip-stay]').tooltip('show');
  198. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  199. $('.content-main').addClass('on-edit');
  200. });
  201. $('a[data-toggle="tab"][href="#edit-form"]').on('hide.bs.tab', function() {
  202. $('.content-main').removeClass('on-edit');
  203. });
  204. $('.copy-link').on('click', function () {
  205. $(this).select();
  206. });
  207. $('#createMemo').on('shown.bs.modal', function (e) {
  208. $('#memoName').focus();
  209. });
  210. $('#createMemoForm').submit(function(e)
  211. {
  212. var prefix = $('[name=memoNamePrefix]', this).val();
  213. var name = $('[name=memoName]', this).val();
  214. if (name === '') {
  215. prefix = prefix.slice(0, -1);
  216. }
  217. top.location.href = prefix + name;
  218. return false;
  219. });
  220. $('#renamePage').on('shown.bs.modal', function (e) {
  221. $('#newPageName').focus();
  222. });
  223. $('#renamePageForm').submit(function(e) {
  224. $.ajax({
  225. type: 'POST',
  226. url: '/_api/pages.rename',
  227. data: $('#renamePageForm').serialize(),
  228. dataType: 'json'
  229. }).done(function(res) {
  230. if (!res.ok) {
  231. $('#newPageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  232. $('#newPageNameCheck').addClass('alert-danger');
  233. } else {
  234. var page = res.page;
  235. var path = $('#pagePath').html();
  236. $('#newPageNameCheck').removeClass('alert-danger');
  237. $('#newPageNameCheck').html('<img src="/images/loading_s.gif"> 移動しました。移動先にジャンプします。');
  238. setTimeout(function() {
  239. top.location.href = page.path + '?renamed=' + path;
  240. }, 1000);
  241. }
  242. });
  243. return false;
  244. });
  245. $('#create-portal-button').on('click', function(e) {
  246. $('.portal').removeClass('hide');
  247. $('.content-main').addClass('on-edit');
  248. $('.portal a[data-toggle="tab"][href="#edit-form"]').tab('show');
  249. var path = $('.content-main').data('path');
  250. if (path != '/' && $('.content-main').data('page-id') == '') {
  251. var upperPage = path.substr(0, path.length - 1);
  252. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  253. if (res.ok && res.page) {
  254. $('#portal-warning-modal').modal('show');
  255. }
  256. });
  257. }
  258. });
  259. $('#portal-form-close').on('click', function(e) {
  260. $('.portal').addClass('hide');
  261. $('.content-main').removeClass('on-edit');
  262. return false;
  263. });
  264. // list-link
  265. $('.page-list-link').each(function() {
  266. var $link = $(this);
  267. var text = $link.text();
  268. var path = $link.data('path');
  269. var shortPath = $link.data('short-path');
  270. $link.html(path.replace(new RegExp(shortPath + '(/)?$'), '<strong>' + shortPath + '$1</strong>'));
  271. });
  272. if (pageId) {
  273. // if page exists
  274. var $rawTextOriginal = $('#raw-text-original');
  275. if ($rawTextOriginal.length > 0) {
  276. var renderer = new Crowi.renderer($('#raw-text-original').html());
  277. renderer.render();
  278. Crowi.correctHeaders('#revision-body-content');
  279. Crowi.revisionToc('#revision-body-content', '#revision-toc');
  280. }
  281. // header
  282. var $header = $('#page-header');
  283. if ($header.length > 0) {
  284. var headerHeight = $header.outerHeight(true);
  285. $('.header-wrap').css({height: (headerHeight + 16) + 'px'});
  286. $header.affix({
  287. offset: {
  288. top: function() {
  289. return headerHeight + 86; // (54 header + 16 header padding-top + 16 content padding-top)
  290. }
  291. }
  292. });
  293. $('[data-affix-disable]').on('click', function(e) {
  294. $elm = $($(this).data('affix-disable'));
  295. $(window).off('.affix');
  296. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  297. return false;
  298. });
  299. }
  300. // omg
  301. function createCommentHTML(revision, creator, comment, commentedAt) {
  302. var $comment = $('<div>');
  303. var $commentImage = $('<img class="picture picture-rounded">')
  304. .attr('src', Crowi.userPicture(creator));
  305. var $commentCreator = $('<div class="page-comment-creator">')
  306. .text(creator.username);
  307. var $commentRevision = $('<a class="page-comment-revision label">')
  308. .attr('href', '?revision=' + revision)
  309. .text(revision.substr(0,8));
  310. if (revision !== revisionId) {
  311. $commentRevision.addClass('label-default');
  312. } else {
  313. $commentRevision.addClass('label-primary');
  314. }
  315. var $commentMeta = $('<div class="page-comment-meta">')
  316. .text(commentedAt + ' ')
  317. .append($commentRevision);
  318. var $commentBody = $('<div class="page-comment-body">')
  319. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  320. var $commentMain = $('<div class="page-comment-main">')
  321. .append($commentCreator)
  322. .append($commentBody)
  323. .append($commentMeta)
  324. $comment.addClass('page-comment');
  325. if (creator._id === currentUser) {
  326. $comment.addClass('page-comment-me');
  327. }
  328. if (revision !== revisionId) {
  329. $comment.addClass('page-comment-old');
  330. }
  331. $comment
  332. .append($commentImage)
  333. .append($commentMain);
  334. return $comment;
  335. }
  336. // get comments
  337. var $pageCommentList = $('.page-comments-list');
  338. var $pageCommentListNewer = $('#page-comments-list-newer');
  339. var $pageCommentListCurrent = $('#page-comments-list-current');
  340. var $pageCommentListOlder = $('#page-comments-list-older');
  341. var hasNewer = false;
  342. var hasOlder = false;
  343. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  344. if (res.ok) {
  345. var comments = res.comments;
  346. $.each(comments, function(i, comment) {
  347. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  348. if (comment.revision == revisionId) {
  349. $pageCommentListCurrent.append(commentContent);
  350. } else {
  351. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  352. $pageCommentListNewer.append(commentContent);
  353. hasNewer = true;
  354. } else {
  355. $pageCommentListOlder.append(commentContent);
  356. hasOlder = true;
  357. }
  358. }
  359. });
  360. }
  361. }).fail(function(data) {
  362. }).always(function() {
  363. if (!hasNewer) {
  364. $('.page-comments-list-toggle-newer').hide();
  365. }
  366. if (!hasOlder) {
  367. $pageCommentListOlder.addClass('collapse');
  368. $('.page-comments-list-toggle-older').hide();
  369. }
  370. });
  371. // post comment event
  372. $('#page-comment-form').on('submit', function() {
  373. $button = $('#commenf-form-button');
  374. $button.attr('disabled', 'disabled');
  375. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  376. $button.removeAttr('disabled');
  377. if (data.ok) {
  378. var comment = data.comment;
  379. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  380. $('#comment-form-comment').val('');
  381. $('#comment-form-message').text('');
  382. } else {
  383. $('#comment-form-message').text(data.error);
  384. }
  385. }).fail(function(data) {
  386. if (data.status !== 200) {
  387. $('#comment-form-message').text(data.statusText);
  388. }
  389. });
  390. return false;
  391. });
  392. // attachment
  393. var $pageAttachmentList = $('.page-attachments ul');
  394. $.get('/_api/attachment/page/' + pageId, function(res) {
  395. var attachments = res.data.attachments;
  396. if (attachments.length > 0) {
  397. $.each(attachments, function(i, file) {
  398. $pageAttachmentList.append(
  399. '<li><a href="' + file.fileUrl + '">' + (file.originalName || file.fileName) + '</a> <span class="label label-default">' + file.fileFormat + '</span></li>'
  400. );
  401. })
  402. } else {
  403. $('.page-attachments').remove();
  404. }
  405. });
  406. // bookmark
  407. var $bookmarkButton = $('#bookmark-button');
  408. $.get('/_api/bookmarks.get', {page_id: pageId}, function(res) {
  409. if (res.ok) {
  410. if (res.bookmark) {
  411. MarkBookmarked();
  412. }
  413. }
  414. });
  415. $bookmarkButton.click(function() {
  416. var bookmarked = $bookmarkButton.data('bookmarked');
  417. if (!bookmarked) {
  418. $.post('/_api/bookmarks.add', {page_id: pageId}, function(res) {
  419. if (res.ok && res.bookmark) {
  420. MarkBookmarked();
  421. }
  422. });
  423. } else {
  424. $.post('/_api/bookmarks.remove', {page_id: pageId}, function(res) {
  425. if (res.ok) {
  426. MarkUnBookmarked();
  427. }
  428. });
  429. }
  430. return false;
  431. });
  432. function MarkBookmarked()
  433. {
  434. $('i', $bookmarkButton)
  435. .removeClass('fa-star-o')
  436. .addClass('fa-star');
  437. $bookmarkButton.data('bookmarked', 1);
  438. }
  439. function MarkUnBookmarked()
  440. {
  441. $('i', $bookmarkButton)
  442. .removeClass('fa-star')
  443. .addClass('fa-star-o');
  444. $bookmarkButton.data('bookmarked', 0);
  445. }
  446. // Like
  447. var $likeButton = $('#like-button');
  448. var $likeCount = $('#like-count');
  449. $likeButton.click(function() {
  450. var liked = $likeButton.data('liked');
  451. if (!liked) {
  452. $.post('/_api/likes.add', {page_id: pageId}, function(res) {
  453. if (res.ok) {
  454. MarkLiked();
  455. }
  456. });
  457. } else {
  458. $.post('/_api/likes.remove', {page_id: pageId}, function(res) {
  459. if (res.ok) {
  460. MarkUnLiked();
  461. }
  462. });
  463. }
  464. return false;
  465. });
  466. var $likerList = $("#liker-list");
  467. var likers = $likerList.data('likers');
  468. if (likers && likers.length > 0) {
  469. // FIXME: user data cache
  470. $.get('/_api/users.list', {user_ids: likers}, function(res) {
  471. // ignore unless response has error
  472. if (res.ok) {
  473. AddToLikers(res.users);
  474. }
  475. });
  476. }
  477. function AddToLikers (users) {
  478. $.each(users, function(i, user) {
  479. $likerList.append(CreateUserLinkWithPicture(user));
  480. });
  481. }
  482. function MarkLiked()
  483. {
  484. $likeButton.addClass('active');
  485. $likeButton.data('liked', 1);
  486. $likeCount.text(parseInt($likeCount.text()) + 1);
  487. }
  488. function MarkUnLiked()
  489. {
  490. $likeButton.removeClass('active');
  491. $likeButton.data('liked', 0);
  492. $likeCount.text(parseInt($likeCount.text()) - 1);
  493. }
  494. if (!isSeen) {
  495. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  496. // ignore unless response has error
  497. if (res.ok && res.seenUser) {
  498. $('#content-main').data('page-is-seen', 1);
  499. }
  500. });
  501. }
  502. var $seenUserList = $("#seen-user-list");
  503. var seenUsers = $seenUserList.data('seen-users');
  504. var seenUsersArray = seenUsers.split(',');
  505. if (seenUsers && seenUsersArray.length > 0 && seenUsersArray.length <= 10) {
  506. // FIXME: user data cache
  507. $.get('/_api/users.list', {user_ids: seenUsers}, function(res) {
  508. // ignore unless response has error
  509. if (res.ok) {
  510. AddToSeenUser(res.users);
  511. }
  512. });
  513. }
  514. function CreateUserLinkWithPicture (user) {
  515. var $userHtml = $('<a>');
  516. $userHtml.data('user-id', user._id);
  517. $userHtml.attr('href', '/user/' + user.username);
  518. $userHtml.attr('title', user.name);
  519. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  520. $userPicture.attr('alt', user.name);
  521. $userPicture.attr('src', Crowi.userPicture(user));
  522. $userHtml.append($userPicture);
  523. return $userHtml;
  524. }
  525. function AddToSeenUser (users) {
  526. $.each(users, function(i, user) {
  527. $seenUserList.append(CreateUserLinkWithPicture(user));
  528. });
  529. }
  530. }
  531. });