crowi.js 16 KB

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