crowi.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. var pagePath= $('#content-main').data('path');
  196. Crowi.linkPath();
  197. $('[data-toggle="tooltip"]').tooltip();
  198. $('[data-tooltip-stay]').tooltip('show');
  199. $('.copy-link').on('click', function () {
  200. $(this).select();
  201. });
  202. $('#createMemo').on('shown.bs.modal', function (e) {
  203. $('#memoName').focus();
  204. });
  205. $('#createMemoForm').submit(function(e)
  206. {
  207. var prefix = $('[name=memoNamePrefix]', this).val();
  208. var name = $('[name=memoName]', this).val();
  209. if (name === '') {
  210. prefix = prefix.slice(0, -1);
  211. }
  212. top.location.href = prefix + name;
  213. return false;
  214. });
  215. $('#renamePage').on('shown.bs.modal', function (e) {
  216. $('#newPageName').focus();
  217. });
  218. $('#renamePageForm').submit(function(e) {
  219. $.ajax({
  220. type: 'POST',
  221. url: '/_api/pages.rename',
  222. data: $('#renamePageForm').serialize(),
  223. dataType: 'json'
  224. }).done(function(res) {
  225. if (!res.ok) {
  226. $('#newPageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  227. $('#newPageNameCheck').addClass('alert-danger');
  228. } else {
  229. var page = res.page;
  230. var path = $('#pagePath').html();
  231. $('#newPageNameCheck').removeClass('alert-danger');
  232. $('#newPageNameCheck').html('<img src="/images/loading_s.gif"> 移動しました。移動先にジャンプします。');
  233. setTimeout(function() {
  234. top.location.href = page.path + '?renamed=' + path;
  235. }, 1000);
  236. }
  237. });
  238. return false;
  239. });
  240. $('#create-portal-button').on('click', function(e) {
  241. $('.portal').removeClass('hide');
  242. $('.content-main').addClass('on-edit');
  243. $('.portal a[data-toggle="tab"][href="#edit-form"]').tab('show');
  244. var path = $('.content-main').data('path');
  245. if (path != '/' && $('.content-main').data('page-id') == '') {
  246. var upperPage = path.substr(0, path.length - 1);
  247. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  248. if (res.ok && res.page) {
  249. $('#portal-warning-modal').modal('show');
  250. }
  251. });
  252. }
  253. });
  254. $('#portal-form-close').on('click', function(e) {
  255. $('.portal').addClass('hide');
  256. $('.content-main').removeClass('on-edit');
  257. return false;
  258. });
  259. // list-link
  260. $('.page-list-link').each(function() {
  261. var $link = $(this);
  262. var text = $link.text();
  263. var path = $link.data('path');
  264. var shortPath = $link.data('short-path');
  265. $link.html(path.replace(new RegExp(shortPath + '(/)?$'), '<strong>' + shortPath + '$1</strong>'));
  266. });
  267. if (pageId) {
  268. // if page exists
  269. var $rawTextOriginal = $('#raw-text-original');
  270. if ($rawTextOriginal.length > 0) {
  271. var renderer = new Crowi.renderer($('#raw-text-original').html());
  272. renderer.render();
  273. Crowi.correctHeaders('#revision-body-content');
  274. Crowi.revisionToc('#revision-body-content', '#revision-toc');
  275. }
  276. // header
  277. var $header = $('#page-header');
  278. if ($header.length > 0) {
  279. var headerHeight = $header.outerHeight(true);
  280. $('.header-wrap').css({height: (headerHeight + 16) + 'px'});
  281. $header.affix({
  282. offset: {
  283. top: function() {
  284. return headerHeight + 86; // (54 header + 16 header padding-top + 16 content padding-top)
  285. }
  286. }
  287. });
  288. $('[data-affix-disable]').on('click', function(e) {
  289. $elm = $($(this).data('affix-disable'));
  290. $(window).off('.affix');
  291. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  292. return false;
  293. });
  294. }
  295. // omg
  296. function createCommentHTML(revision, creator, comment, commentedAt) {
  297. var $comment = $('<div>');
  298. var $commentImage = $('<img class="picture picture-rounded">')
  299. .attr('src', Crowi.userPicture(creator));
  300. var $commentCreator = $('<div class="page-comment-creator">')
  301. .text(creator.username);
  302. var $commentRevision = $('<a class="page-comment-revision label">')
  303. .attr('href', '?revision=' + revision)
  304. .text(revision.substr(0,8));
  305. if (revision !== revisionId) {
  306. $commentRevision.addClass('label-default');
  307. } else {
  308. $commentRevision.addClass('label-primary');
  309. }
  310. var $commentMeta = $('<div class="page-comment-meta">')
  311. .text(commentedAt + ' ')
  312. .append($commentRevision);
  313. var $commentBody = $('<div class="page-comment-body">')
  314. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  315. var $commentMain = $('<div class="page-comment-main">')
  316. .append($commentCreator)
  317. .append($commentBody)
  318. .append($commentMeta)
  319. $comment.addClass('page-comment');
  320. if (creator._id === currentUser) {
  321. $comment.addClass('page-comment-me');
  322. }
  323. if (revision !== revisionId) {
  324. $comment.addClass('page-comment-old');
  325. }
  326. $comment
  327. .append($commentImage)
  328. .append($commentMain);
  329. return $comment;
  330. }
  331. // get comments
  332. var $pageCommentList = $('.page-comments-list');
  333. var $pageCommentListNewer = $('#page-comments-list-newer');
  334. var $pageCommentListCurrent = $('#page-comments-list-current');
  335. var $pageCommentListOlder = $('#page-comments-list-older');
  336. var hasNewer = false;
  337. var hasOlder = false;
  338. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  339. if (res.ok) {
  340. var comments = res.comments;
  341. $.each(comments, function(i, comment) {
  342. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  343. if (comment.revision == revisionId) {
  344. $pageCommentListCurrent.append(commentContent);
  345. } else {
  346. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  347. $pageCommentListNewer.append(commentContent);
  348. hasNewer = true;
  349. } else {
  350. $pageCommentListOlder.append(commentContent);
  351. hasOlder = true;
  352. }
  353. }
  354. });
  355. }
  356. }).fail(function(data) {
  357. }).always(function() {
  358. if (!hasNewer) {
  359. $('.page-comments-list-toggle-newer').hide();
  360. }
  361. if (!hasOlder) {
  362. $pageCommentListOlder.addClass('collapse');
  363. $('.page-comments-list-toggle-older').hide();
  364. }
  365. });
  366. // post comment event
  367. $('#page-comment-form').on('submit', function() {
  368. $button = $('#commenf-form-button');
  369. $button.attr('disabled', 'disabled');
  370. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  371. $button.removeAttr('disabled');
  372. if (data.ok) {
  373. var comment = data.comment;
  374. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  375. $('#comment-form-comment').val('');
  376. $('#comment-form-message').text('');
  377. } else {
  378. $('#comment-form-message').text(data.error);
  379. }
  380. }).fail(function(data) {
  381. if (data.status !== 200) {
  382. $('#comment-form-message').text(data.statusText);
  383. }
  384. });
  385. return false;
  386. });
  387. // attachment
  388. var $pageAttachmentList = $('.page-attachments ul');
  389. $.get('/_api/attachment/page/' + pageId, function(res) {
  390. var attachments = res.data.attachments;
  391. if (attachments.length > 0) {
  392. $.each(attachments, function(i, file) {
  393. $pageAttachmentList.append(
  394. '<li><a href="' + file.fileUrl + '">' + (file.originalName || file.fileName) + '</a> <span class="label label-default">' + file.fileFormat + '</span></li>'
  395. );
  396. })
  397. } else {
  398. $('.page-attachments').remove();
  399. }
  400. });
  401. // bookmark
  402. var $bookmarkButton = $('#bookmark-button');
  403. $.get('/_api/bookmarks.get', {page_id: pageId}, function(res) {
  404. if (res.ok) {
  405. if (res.bookmark) {
  406. MarkBookmarked();
  407. }
  408. }
  409. });
  410. $bookmarkButton.click(function() {
  411. var bookmarked = $bookmarkButton.data('bookmarked');
  412. if (!bookmarked) {
  413. $.post('/_api/bookmarks.add', {page_id: pageId}, function(res) {
  414. if (res.ok && res.bookmark) {
  415. MarkBookmarked();
  416. }
  417. });
  418. } else {
  419. $.post('/_api/bookmarks.remove', {page_id: pageId}, function(res) {
  420. if (res.ok) {
  421. MarkUnBookmarked();
  422. }
  423. });
  424. }
  425. return false;
  426. });
  427. function MarkBookmarked()
  428. {
  429. $('i', $bookmarkButton)
  430. .removeClass('fa-star-o')
  431. .addClass('fa-star');
  432. $bookmarkButton.data('bookmarked', 1);
  433. }
  434. function MarkUnBookmarked()
  435. {
  436. $('i', $bookmarkButton)
  437. .removeClass('fa-star')
  438. .addClass('fa-star-o');
  439. $bookmarkButton.data('bookmarked', 0);
  440. }
  441. // Like
  442. var $likeButton = $('#like-button');
  443. var $likeCount = $('#like-count');
  444. $likeButton.click(function() {
  445. var liked = $likeButton.data('liked');
  446. if (!liked) {
  447. $.post('/_api/likes.add', {page_id: pageId}, function(res) {
  448. if (res.ok) {
  449. MarkLiked();
  450. }
  451. });
  452. } else {
  453. $.post('/_api/likes.remove', {page_id: pageId}, function(res) {
  454. if (res.ok) {
  455. MarkUnLiked();
  456. }
  457. });
  458. }
  459. return false;
  460. });
  461. var $likerList = $("#liker-list");
  462. var likers = $likerList.data('likers');
  463. if (likers && likers.length > 0) {
  464. // FIXME: user data cache
  465. $.get('/_api/users.list', {user_ids: likers}, function(res) {
  466. // ignore unless response has error
  467. if (res.ok) {
  468. AddToLikers(res.users);
  469. }
  470. });
  471. }
  472. function AddToLikers (users) {
  473. $.each(users, function(i, user) {
  474. $likerList.append(CreateUserLinkWithPicture(user));
  475. });
  476. }
  477. function MarkLiked()
  478. {
  479. $likeButton.addClass('active');
  480. $likeButton.data('liked', 1);
  481. $likeCount.text(parseInt($likeCount.text()) + 1);
  482. }
  483. function MarkUnLiked()
  484. {
  485. $likeButton.removeClass('active');
  486. $likeButton.data('liked', 0);
  487. $likeCount.text(parseInt($likeCount.text()) - 1);
  488. }
  489. if (!isSeen) {
  490. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  491. // ignore unless response has error
  492. if (res.ok && res.seenUser) {
  493. $('#content-main').data('page-is-seen', 1);
  494. }
  495. });
  496. }
  497. var $seenUserList = $("#seen-user-list");
  498. var seenUsers = $seenUserList.data('seen-users');
  499. var seenUsersArray = seenUsers.split(',');
  500. if (seenUsers && seenUsersArray.length > 0 && seenUsersArray.length <= 10) {
  501. // FIXME: user data cache
  502. $.get('/_api/users.list', {user_ids: seenUsers}, function(res) {
  503. // ignore unless response has error
  504. if (res.ok) {
  505. AddToSeenUser(res.users);
  506. }
  507. });
  508. }
  509. function CreateUserLinkWithPicture (user) {
  510. var $userHtml = $('<a>');
  511. $userHtml.data('user-id', user._id);
  512. $userHtml.attr('href', '/user/' + user.username);
  513. $userHtml.attr('title', user.name);
  514. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  515. $userPicture.attr('alt', user.name);
  516. $userPicture.attr('src', Crowi.userPicture(user));
  517. $userHtml.append($userPicture);
  518. return $userHtml;
  519. }
  520. function AddToSeenUser (users) {
  521. $.each(users, function(i, user) {
  522. $seenUserList.append(CreateUserLinkWithPicture(user));
  523. });
  524. }
  525. }
  526. });