crowi.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. var path = $('#pagePath').html();
  224. $.ajax({
  225. type: 'POST',
  226. url: '/_api/page_rename' + path,
  227. data: $('#renamePageForm').serialize(),
  228. dataType: 'json'
  229. }).done(function(data) {
  230. if (!data.status) {
  231. $('#newPageNameCheck').html('<i class="fa fa-times-circle"></i> ' + data.message);
  232. $('#newPageNameCheck').addClass('alert-danger');
  233. } else {
  234. $('#newPageNameCheck').removeClass('alert-danger');
  235. $('#newPageNameCheck').html('<img src="/images/loading_s.gif"> 移動しました。移動先にジャンプします。');
  236. setTimeout(function() {
  237. top.location.href = data.page.path + '?renamed=' + path;
  238. }, 1000);
  239. }
  240. });
  241. return false;
  242. });
  243. $('#create-portal-button').on('click', function(e) {
  244. $('.portal').removeClass('hide');
  245. $('.content-main').addClass('on-edit');
  246. $('.portal a[data-toggle="tab"][href="#edit-form"]').tab('show');
  247. });
  248. $('#portal-form-close').on('click', function(e) {
  249. $('.portal').addClass('hide');
  250. $('.content-main').removeClass('on-edit');
  251. return false;
  252. });
  253. if (pageId) {
  254. // omg
  255. function createCommentHTML(revision, creator, comment, commentedAt) {
  256. var $comment = $('<div>');
  257. var $commentImage = $('<img class="picture picture-rounded">')
  258. .attr('src', Crowi.userPicture(creator));
  259. var $commentCreator = $('<div class="page-comment-creator">')
  260. .text(creator.username);
  261. var $commentRevision = $('<a class="page-comment-revision label">')
  262. .attr('href', '?revision=' + revision)
  263. .text(revision.substr(0,8));
  264. if (revision !== revisionId) {
  265. $commentRevision.addClass('label-default');
  266. } else {
  267. $commentRevision.addClass('label-primary');
  268. }
  269. var $commentMeta = $('<div class="page-comment-meta">')
  270. .text(commentedAt + ' ')
  271. .append($commentRevision);
  272. var $commentBody = $('<div class="page-comment-body">')
  273. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  274. var $commentMain = $('<div class="page-comment-main">')
  275. .append($commentCreator)
  276. .append($commentBody)
  277. .append($commentMeta)
  278. $comment.addClass('page-comment');
  279. if (creator._id === currentUser) {
  280. $comment.addClass('page-comment-me');
  281. }
  282. if (revision !== revisionId) {
  283. $comment.addClass('page-comment-old');
  284. }
  285. $comment
  286. .append($commentImage)
  287. .append($commentMain);
  288. return $comment;
  289. }
  290. // get comments
  291. var $pageCommentList = $('.page-comments-list');
  292. var $pageCommentListNewer = $('#page-comments-list-newer');
  293. var $pageCommentListCurrent = $('#page-comments-list-current');
  294. var $pageCommentListOlder = $('#page-comments-list-older');
  295. var hasNewer = false;
  296. var hasOlder = false;
  297. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  298. if (res.ok) {
  299. var comments = res.comments;
  300. $.each(comments, function(i, comment) {
  301. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  302. if (comment.revision == revisionId) {
  303. $pageCommentListCurrent.append(commentContent);
  304. } else {
  305. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  306. $pageCommentListNewer.append(commentContent);
  307. hasNewer = true;
  308. } else {
  309. $pageCommentListOlder.append(commentContent);
  310. hasOlder = true;
  311. }
  312. }
  313. });
  314. }
  315. }).fail(function(data) {
  316. }).always(function() {
  317. if (!hasNewer) {
  318. $('.page-comments-list-toggle-newer').hide();
  319. }
  320. if (!hasOlder) {
  321. $pageCommentListOlder.addClass('collapse');
  322. $('.page-comments-list-toggle-older').hide();
  323. }
  324. });
  325. // post comment event
  326. $('#page-comment-form').on('submit', function() {
  327. $button = $('#commenf-form-button');
  328. $button.attr('disabled', 'disabled');
  329. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  330. $button.removeAttr('disabled');
  331. if (data.ok) {
  332. var comment = data.comment;
  333. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  334. $('#comment-form-comment').val('');
  335. $('#comment-form-message').text('');
  336. } else {
  337. $('#comment-form-message').text(data.error);
  338. }
  339. }).fail(function(data) {
  340. if (data.status !== 200) {
  341. $('#comment-form-message').text(data.statusText);
  342. }
  343. });
  344. return false;
  345. });
  346. // attachment
  347. var $pageAttachmentList = $('.page-attachments ul');
  348. $.get('/_api/attachment/page/' + pageId, function(res) {
  349. var attachments = res.data.attachments;
  350. var urlBase = res.data.fileBaseUrl;
  351. if (attachments.length > 0) {
  352. $.each(attachments, function(i, file) {
  353. $pageAttachmentList.append(
  354. '<li><a href="' + urlBase + file.filePath + '">' + (file.originalName || file.fileName) + '</a> <span class="label label-default">' + file.fileFormat + '</span></li>'
  355. );
  356. })
  357. } else {
  358. $('.page-attachments').remove();
  359. }
  360. });
  361. // bookmark
  362. var $bookmarkButton = $('#bookmark-button');
  363. $.get('/_api/bookmarks.get', {page_id: pageId}, function(res) {
  364. if (res.ok) {
  365. if (res.bookmark) {
  366. MarkBookmarked();
  367. }
  368. }
  369. });
  370. $bookmarkButton.click(function() {
  371. var bookmarked = $bookmarkButton.data('bookmarked');
  372. if (!bookmarked) {
  373. $.post('/_api/bookmarks.add', {page_id: pageId}, function(res) {
  374. if (res.ok && res.bookmark) {
  375. MarkBookmarked();
  376. }
  377. });
  378. } else {
  379. $.post('/_api/bookmarks.remove', {page_id: pageId}, function(res) {
  380. if (res.ok) {
  381. MarkUnBookmarked();
  382. }
  383. });
  384. }
  385. return false;
  386. });
  387. function MarkBookmarked()
  388. {
  389. $('i', $bookmarkButton)
  390. .removeClass('fa-star-o')
  391. .addClass('fa-star');
  392. $bookmarkButton.data('bookmarked', 1);
  393. }
  394. function MarkUnBookmarked()
  395. {
  396. $('i', $bookmarkButton)
  397. .removeClass('fa-star')
  398. .addClass('fa-star-o');
  399. $bookmarkButton.data('bookmarked', 0);
  400. }
  401. // Like
  402. var $likeButton = $('#like-button');
  403. var $likeCount = $('#like-count');
  404. $likeButton.click(function() {
  405. var liked = $likeButton.data('liked');
  406. if (!liked) {
  407. $.post('/_api/likes.add', {page_id: pageId}, function(res) {
  408. if (res.ok) {
  409. MarkLiked();
  410. }
  411. });
  412. } else {
  413. $.post('/_api/likes.remove', {page_id: pageId}, function(res) {
  414. if (res.ok) {
  415. MarkUnLiked();
  416. }
  417. });
  418. }
  419. return false;
  420. });
  421. var $likerList = $("#liker-list");
  422. var likers = $likerList.data('likers');
  423. if (likers && likers.length > 0) {
  424. // FIXME: user data cache
  425. $.get('/_api/users.list', {user_ids: likers}, function(res) {
  426. // ignore unless response has error
  427. if (res.ok) {
  428. AddToLikers(res.users);
  429. }
  430. });
  431. }
  432. function AddToLikers (users) {
  433. $.each(users, function(i, user) {
  434. $likerList.append(CreateUserLinkWithPicture(user));
  435. });
  436. }
  437. function MarkLiked()
  438. {
  439. $likeButton.addClass('active');
  440. $likeButton.data('liked', 1);
  441. $likeCount.text(parseInt($likeCount.text()) + 1);
  442. }
  443. function MarkUnLiked()
  444. {
  445. $likeButton.removeClass('active');
  446. $likeButton.data('liked', 0);
  447. $likeCount.text(parseInt($likeCount.text()) - 1);
  448. }
  449. if (!isSeen) {
  450. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  451. // ignore unless response has error
  452. if (res.ok && res.seenUser) {
  453. $('#content-main').data('page-is-seen', 1);
  454. }
  455. });
  456. }
  457. var $seenUserList = $("#seen-user-list");
  458. var seenUsers = $seenUserList.data('seen-users');
  459. if (seenUsers && seenUsers.length > 0) {
  460. // FIXME: user data cache
  461. $.get('/_api/users.list', {user_ids: seenUsers}, function(res) {
  462. // ignore unless response has error
  463. if (res.ok) {
  464. AddToSeenUser(res.users);
  465. }
  466. });
  467. }
  468. function CreateUserLinkWithPicture (user) {
  469. var $userHtml = $('<a>');
  470. $userHtml.data('user-id', user._id);
  471. $userHtml.attr('href', '/user/' + user.username);
  472. $userHtml.attr('title', user.name);
  473. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  474. $userPicture.attr('alt', user.name);
  475. $userPicture.attr('src', Crowi.userPicture(user));
  476. $userHtml.append($userPicture);
  477. return $userHtml;
  478. }
  479. function AddToSeenUser (users) {
  480. $.each(users, function(i, user) {
  481. $seenUserList.append(CreateUserLinkWithPicture(user));
  482. });
  483. }
  484. }
  485. });