crowi.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. // omg
  274. function createCommentHTML(revision, creator, comment, commentedAt) {
  275. var $comment = $('<div>');
  276. var $commentImage = $('<img class="picture picture-rounded">')
  277. .attr('src', Crowi.userPicture(creator));
  278. var $commentCreator = $('<div class="page-comment-creator">')
  279. .text(creator.username);
  280. var $commentRevision = $('<a class="page-comment-revision label">')
  281. .attr('href', '?revision=' + revision)
  282. .text(revision.substr(0,8));
  283. if (revision !== revisionId) {
  284. $commentRevision.addClass('label-default');
  285. } else {
  286. $commentRevision.addClass('label-primary');
  287. }
  288. var $commentMeta = $('<div class="page-comment-meta">')
  289. .text(commentedAt + ' ')
  290. .append($commentRevision);
  291. var $commentBody = $('<div class="page-comment-body">')
  292. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  293. var $commentMain = $('<div class="page-comment-main">')
  294. .append($commentCreator)
  295. .append($commentBody)
  296. .append($commentMeta)
  297. $comment.addClass('page-comment');
  298. if (creator._id === currentUser) {
  299. $comment.addClass('page-comment-me');
  300. }
  301. if (revision !== revisionId) {
  302. $comment.addClass('page-comment-old');
  303. }
  304. $comment
  305. .append($commentImage)
  306. .append($commentMain);
  307. return $comment;
  308. }
  309. // get comments
  310. var $pageCommentList = $('.page-comments-list');
  311. var $pageCommentListNewer = $('#page-comments-list-newer');
  312. var $pageCommentListCurrent = $('#page-comments-list-current');
  313. var $pageCommentListOlder = $('#page-comments-list-older');
  314. var hasNewer = false;
  315. var hasOlder = false;
  316. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  317. if (res.ok) {
  318. var comments = res.comments;
  319. $.each(comments, function(i, comment) {
  320. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  321. if (comment.revision == revisionId) {
  322. $pageCommentListCurrent.append(commentContent);
  323. } else {
  324. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  325. $pageCommentListNewer.append(commentContent);
  326. hasNewer = true;
  327. } else {
  328. $pageCommentListOlder.append(commentContent);
  329. hasOlder = true;
  330. }
  331. }
  332. });
  333. }
  334. }).fail(function(data) {
  335. }).always(function() {
  336. if (!hasNewer) {
  337. $('.page-comments-list-toggle-newer').hide();
  338. }
  339. if (!hasOlder) {
  340. $pageCommentListOlder.addClass('collapse');
  341. $('.page-comments-list-toggle-older').hide();
  342. }
  343. });
  344. // post comment event
  345. $('#page-comment-form').on('submit', function() {
  346. $button = $('#commenf-form-button');
  347. $button.attr('disabled', 'disabled');
  348. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  349. $button.removeAttr('disabled');
  350. if (data.ok) {
  351. var comment = data.comment;
  352. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  353. $('#comment-form-comment').val('');
  354. $('#comment-form-message').text('');
  355. } else {
  356. $('#comment-form-message').text(data.error);
  357. }
  358. }).fail(function(data) {
  359. if (data.status !== 200) {
  360. $('#comment-form-message').text(data.statusText);
  361. }
  362. });
  363. return false;
  364. });
  365. // attachment
  366. var $pageAttachmentList = $('.page-attachments ul');
  367. $.get('/_api/attachment/page/' + pageId, function(res) {
  368. var attachments = res.data.attachments;
  369. if (attachments.length > 0) {
  370. $.each(attachments, function(i, file) {
  371. $pageAttachmentList.append(
  372. '<li><a href="' + file.fileUrl + '">' + (file.originalName || file.fileName) + '</a> <span class="label label-default">' + file.fileFormat + '</span></li>'
  373. );
  374. })
  375. } else {
  376. $('.page-attachments').remove();
  377. }
  378. });
  379. // bookmark
  380. var $bookmarkButton = $('#bookmark-button');
  381. $.get('/_api/bookmarks.get', {page_id: pageId}, function(res) {
  382. if (res.ok) {
  383. if (res.bookmark) {
  384. MarkBookmarked();
  385. }
  386. }
  387. });
  388. $bookmarkButton.click(function() {
  389. var bookmarked = $bookmarkButton.data('bookmarked');
  390. if (!bookmarked) {
  391. $.post('/_api/bookmarks.add', {page_id: pageId}, function(res) {
  392. if (res.ok && res.bookmark) {
  393. MarkBookmarked();
  394. }
  395. });
  396. } else {
  397. $.post('/_api/bookmarks.remove', {page_id: pageId}, function(res) {
  398. if (res.ok) {
  399. MarkUnBookmarked();
  400. }
  401. });
  402. }
  403. return false;
  404. });
  405. function MarkBookmarked()
  406. {
  407. $('i', $bookmarkButton)
  408. .removeClass('fa-star-o')
  409. .addClass('fa-star');
  410. $bookmarkButton.data('bookmarked', 1);
  411. }
  412. function MarkUnBookmarked()
  413. {
  414. $('i', $bookmarkButton)
  415. .removeClass('fa-star')
  416. .addClass('fa-star-o');
  417. $bookmarkButton.data('bookmarked', 0);
  418. }
  419. // Like
  420. var $likeButton = $('#like-button');
  421. var $likeCount = $('#like-count');
  422. $likeButton.click(function() {
  423. var liked = $likeButton.data('liked');
  424. if (!liked) {
  425. $.post('/_api/likes.add', {page_id: pageId}, function(res) {
  426. if (res.ok) {
  427. MarkLiked();
  428. }
  429. });
  430. } else {
  431. $.post('/_api/likes.remove', {page_id: pageId}, function(res) {
  432. if (res.ok) {
  433. MarkUnLiked();
  434. }
  435. });
  436. }
  437. return false;
  438. });
  439. var $likerList = $("#liker-list");
  440. var likers = $likerList.data('likers');
  441. if (likers && likers.length > 0) {
  442. // FIXME: user data cache
  443. $.get('/_api/users.list', {user_ids: likers}, function(res) {
  444. // ignore unless response has error
  445. if (res.ok) {
  446. AddToLikers(res.users);
  447. }
  448. });
  449. }
  450. function AddToLikers (users) {
  451. $.each(users, function(i, user) {
  452. $likerList.append(CreateUserLinkWithPicture(user));
  453. });
  454. }
  455. function MarkLiked()
  456. {
  457. $likeButton.addClass('active');
  458. $likeButton.data('liked', 1);
  459. $likeCount.text(parseInt($likeCount.text()) + 1);
  460. }
  461. function MarkUnLiked()
  462. {
  463. $likeButton.removeClass('active');
  464. $likeButton.data('liked', 0);
  465. $likeCount.text(parseInt($likeCount.text()) - 1);
  466. }
  467. if (!isSeen) {
  468. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  469. // ignore unless response has error
  470. if (res.ok && res.seenUser) {
  471. $('#content-main').data('page-is-seen', 1);
  472. }
  473. });
  474. }
  475. var $seenUserList = $("#seen-user-list");
  476. var seenUsers = $seenUserList.data('seen-users');
  477. if (seenUsers && seenUsers.length > 0 && seenUsers.length <= 10) {
  478. // FIXME: user data cache
  479. $.get('/_api/users.list', {user_ids: seenUsers}, function(res) {
  480. // ignore unless response has error
  481. if (res.ok) {
  482. AddToSeenUser(res.users);
  483. }
  484. });
  485. }
  486. function CreateUserLinkWithPicture (user) {
  487. var $userHtml = $('<a>');
  488. $userHtml.data('user-id', user._id);
  489. $userHtml.attr('href', '/user/' + user.username);
  490. $userHtml.attr('title', user.name);
  491. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  492. $userPicture.attr('alt', user.name);
  493. $userPicture.attr('src', Crowi.userPicture(user));
  494. $userHtml.append($userPicture);
  495. return $userHtml;
  496. }
  497. function AddToSeenUser (users) {
  498. $.each(users, function(i, user) {
  499. $seenUserList.append(CreateUserLinkWithPicture(user));
  500. });
  501. }
  502. }
  503. });