crowi.js 16 KB

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