crowi.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /* jshint browser: true, jquery: true */
  2. /* Author: Sotaro KARASAWA <sotarok@crocos.co.jp>
  3. */
  4. const io = require('socket.io-client');
  5. const entities = require("entities");
  6. const escapeStringRegexp = require('escape-string-regexp');
  7. require('bootstrap-sass');
  8. require('jquery.cookie');
  9. var Crowi = {};
  10. if (!window) {
  11. window = {};
  12. }
  13. window.Crowi = Crowi;
  14. Crowi.createErrorView = function(msg) {
  15. $('#main').prepend($('<p class="alert-message error">' + msg + '</p>'));
  16. };
  17. /**
  18. * append buttons to section headers
  19. */
  20. Crowi.appendEditSectionButtons = function(contentId, markdown) {
  21. const $content = $(contentId || '#revision-body-content');
  22. $('h1,h2,h3,h4,h5,h6', $content).each(function(idx, elm) {
  23. const line = +elm.getAttribute('data-line');
  24. // add button
  25. $(this).append(`
  26. <span class="revision-head-edit-button">
  27. <a href="#edit-form" onClick="Crowi.setCaretLineData(${line})">
  28. <i class="fa fa-edit"></i>
  29. </a>
  30. </span>
  31. `
  32. );
  33. });
  34. };
  35. /**
  36. * set 'data-caret-line' attribute that will be processed when 'shown.bs.tab' event fired
  37. * @param {number} line
  38. */
  39. Crowi.setCaretLineData = function(line) {
  40. const pageEditorDom = document.querySelector('#page-editor');
  41. pageEditorDom.setAttribute('data-caret-line', line);
  42. }
  43. /**
  44. * invoked when;
  45. *
  46. * 1. window loaded
  47. * 2. 'shown.bs.tab' event fired
  48. */
  49. Crowi.setCaretLineAndFocusToEditor = function() {
  50. // get 'data-caret-line' attributes
  51. const pageEditorDom = document.querySelector('#page-editor');
  52. if (pageEditorDom == null) {
  53. return;
  54. }
  55. const line = pageEditorDom.getAttribute('data-caret-line');
  56. if (line != null) {
  57. crowi.setCaretLine(line);
  58. // reset data-caret-line attribute
  59. pageEditorDom.removeAttribute('data-caret-line');
  60. }
  61. // focus
  62. crowi.focusToEditor();
  63. }
  64. // original: middleware.swigFilter
  65. Crowi.userPicture = function (user) {
  66. if (!user) {
  67. return '/images/userpicture.png';
  68. }
  69. return user.image || '/images/userpicture.png';
  70. };
  71. Crowi.modifyScrollTop = function() {
  72. var offset = 10;
  73. var hash = window.location.hash;
  74. if (hash === "") {
  75. return;
  76. }
  77. var pageHeader = document.querySelector('#page-header');
  78. if (!pageHeader) {
  79. return;
  80. }
  81. var pageHeaderRect = pageHeader.getBoundingClientRect();
  82. var sectionHeader = Crowi.findSectionHeader(hash);
  83. if (sectionHeader === null) {
  84. return;
  85. }
  86. var timeout = 0;
  87. if (window.scrollY === 0) {
  88. timeout = 200;
  89. }
  90. setTimeout(function() {
  91. var sectionHeaderRect = sectionHeader.getBoundingClientRect();
  92. if (sectionHeaderRect.top >= pageHeaderRect.bottom) {
  93. return;
  94. }
  95. window.scrollTo(0, (window.scrollY - pageHeaderRect.height - offset));
  96. }, timeout);
  97. }
  98. Crowi.updateCurrentRevision = function(revisionId) {
  99. $('#page-form [name="pageForm[currentRevision]"]').val(revisionId);
  100. }
  101. Crowi.handleKeyEHandler = (event) => {
  102. // ignore when dom that has 'modal in' classes exists
  103. if (document.getElementsByClassName('modal in').length > 0) {
  104. return;
  105. }
  106. // show editor
  107. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  108. event.preventDefault();
  109. }
  110. Crowi.handleKeyCHandler = (event) => {
  111. // ignore when dom that has 'modal in' classes exists
  112. if (document.getElementsByClassName('modal in').length > 0) {
  113. return;
  114. }
  115. // show modal to create a page
  116. $('#create-page').modal();
  117. event.preventDefault();
  118. }
  119. Crowi.handleKeyCtrlSlashHandler = (event) => {
  120. // show modal to create a page
  121. $('#shortcuts-modal').modal('toggle');
  122. event.preventDefault();
  123. }
  124. $(function() {
  125. var config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
  126. var pageId = $('#content-main').data('page-id');
  127. var revisionId = $('#content-main').data('page-revision-id');
  128. var revisionCreatedAt = $('#content-main').data('page-revision-created');
  129. var currentUser = $('#content-main').data('current-user');
  130. var isSeen = $('#content-main').data('page-is-seen');
  131. var pagePath= $('#content-main').data('path');
  132. var isSavedStatesOfTabChanges = config['isSavedStatesOfTabChanges'];
  133. $('[data-toggle="popover"]').popover();
  134. $('[data-toggle="tooltip"]').tooltip();
  135. $('[data-tooltip-stay]').tooltip('show');
  136. $('#toggle-sidebar').click(function(e) {
  137. var $mainContainer = $('.main-container');
  138. if ($mainContainer.hasClass('aside-hidden')) {
  139. $('.main-container').removeClass('aside-hidden');
  140. $.cookie('aside-hidden', 0, { expires: 30, path: '/' });
  141. } else {
  142. $mainContainer.addClass('aside-hidden');
  143. $.cookie('aside-hidden', 1, { expires: 30, path: '/' });
  144. }
  145. return false;
  146. });
  147. if ($.cookie('aside-hidden') == 1) {
  148. $('.main-container').addClass('aside-hidden');
  149. }
  150. $('.copy-link').on('click', function () {
  151. $(this).select();
  152. });
  153. $('#create-page').on('shown.bs.modal', function (e) {
  154. // quick hack: replace from server side rendering "date" to client side "date"
  155. var today = new Date();
  156. var month = ('0' + (today.getMonth() + 1)).slice(-2);
  157. var day = ('0' + today.getDate()).slice(-2);
  158. var dateString = today.getFullYear() + '/' + month + '/' + day;
  159. $('#create-page-today .page-today-suffix').text('/' + dateString + '/');
  160. $('#create-page-today .page-today-input2').data('prefix', '/' + dateString + '/');
  161. var input2Width = $('#create-page-today .col-xs-10').outerWidth() - 1;
  162. var newWidth = input2Width
  163. - $('#create-page-today .page-today-prefix').outerWidth()
  164. - $('#create-page-today .page-today-input1').outerWidth()
  165. - $('#create-page-today .page-today-suffix').outerWidth()
  166. - 42
  167. ;
  168. $('#create-page-today .form-control.page-today-input2').css({width: newWidth}).focus();
  169. });
  170. $('#create-page-today').submit(function(e) {
  171. var prefix1 = $('input.page-today-input1', this).data('prefix');
  172. var input1 = $('input.page-today-input1', this).val();
  173. var prefix2 = $('input.page-today-input2', this).data('prefix');
  174. var input2 = $('input.page-today-input2', this).val();
  175. if (input1 === '') {
  176. prefix1 = 'メモ';
  177. }
  178. if (input2 === '') {
  179. prefix2 = prefix2.slice(0, -1);
  180. }
  181. top.location.href = prefix1 + input1 + prefix2 + input2 + '#edit-form';
  182. return false;
  183. });
  184. $('#create-page-under-tree').submit(function(e) {
  185. var name = $('input', this).val();
  186. if (!name.match(/^\//)) {
  187. name = '/' + name;
  188. }
  189. if (name.match(/.+\/$/)) {
  190. name = name.substr(0, name.length - 1);
  191. }
  192. top.location.href = name + '#edit-form';
  193. return false;
  194. });
  195. // rename
  196. $('#renamePage').on('shown.bs.modal', function (e) {
  197. $('#newPageName').focus();
  198. });
  199. $('#renamePageForm, #unportalize-form').submit(function(e) {
  200. // create name-value map
  201. let nameValueMap = {};
  202. $(this).serializeArray().forEach((obj) => {
  203. nameValueMap[obj.name] = obj.value;
  204. })
  205. $.ajax({
  206. type: 'POST',
  207. url: '/_api/pages.rename',
  208. data: $(this).serialize(),
  209. dataType: 'json'
  210. }).done(function(res) {
  211. if (!res.ok) {
  212. // if already exists
  213. $('#newPageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  214. $('#newPageNameCheck').addClass('alert-danger');
  215. $('#linkToNewPage').html(`
  216. <i class="fa fa-fw fa-arrow-right"></i><a href="${nameValueMap.new_path}">${nameValueMap.new_path}</a>
  217. `);
  218. } else {
  219. var page = res.page;
  220. $('#newPageNameCheck').removeClass('alert-danger');
  221. //$('#newPageNameCheck').html('<img src="/images/loading_s.gif"> 移動しました。移動先にジャンプします。');
  222. // fix
  223. $('#newPageNameCheck').html('<img src="/images/loading_s.gif"> Page moved! Redirecting to new page location.');
  224. setTimeout(function() {
  225. top.location.href = page.path + '?renamed=' + pagePath;
  226. }, 1000);
  227. }
  228. });
  229. return false;
  230. });
  231. // duplicate
  232. $('#duplicatePage').on('shown.bs.modal', function (e) {
  233. $('#duplicatePageName').focus();
  234. });
  235. $('#duplicatePageForm, #unportalize-form').submit(function (e) {
  236. // create name-value map
  237. let nameValueMap = {};
  238. $(this).serializeArray().forEach((obj) => {
  239. nameValueMap[obj.name] = obj.value;
  240. })
  241. $.ajax({
  242. type: 'POST',
  243. url: '/_api/pages.duplicate',
  244. data: $(this).serialize(),
  245. dataType: 'json'
  246. }).done(function (res) {
  247. if (!res.ok) {
  248. // if already exists
  249. $('#duplicatePageNameCheck').html('<i class="fa fa-times-circle"></i> ' + res.error);
  250. $('#duplicatePageNameCheck').addClass('alert-danger');
  251. $('#linkToNewPage').html(`
  252. <i class="fa fa-fw fa-arrow-right"></i><a href="${nameValueMap.new_path}">${nameValueMap.new_path}</a>
  253. `);
  254. } else {
  255. var page = res.page;
  256. $('#duplicatePageNameCheck').removeClass('alert-danger');
  257. $('#duplicatePageNameCheck').html('<img src="/images/loading_s.gif"> Page duplicated! Redirecting to new page location.');
  258. setTimeout(function () {
  259. top.location.href = page.path + '?duplicated=' + pagePath;
  260. }, 1000);
  261. }
  262. });
  263. return false;
  264. });
  265. // delete
  266. $('#delete-page-form').submit(function(e) {
  267. $.ajax({
  268. type: 'POST',
  269. url: '/_api/pages.remove',
  270. data: $('#delete-page-form').serialize(),
  271. dataType: 'json'
  272. }).done(function(res) {
  273. if (!res.ok) {
  274. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  275. $('#delete-errors').addClass('alert-danger');
  276. } else {
  277. var page = res.page;
  278. top.location.href = page.path;
  279. }
  280. });
  281. return false;
  282. });
  283. $('#revert-delete-page-form').submit(function(e) {
  284. $.ajax({
  285. type: 'POST',
  286. url: '/_api/pages.revertRemove',
  287. data: $('#revert-delete-page-form').serialize(),
  288. dataType: 'json'
  289. }).done(function(res) {
  290. if (!res.ok) {
  291. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  292. $('#delete-errors').addClass('alert-danger');
  293. } else {
  294. var page = res.page;
  295. top.location.href = page.path;
  296. }
  297. });
  298. return false;
  299. });
  300. $('#unlink-page-form').submit(function(e) {
  301. $.ajax({
  302. type: 'POST',
  303. url: '/_api/pages.unlink',
  304. data: $('#unlink-page-form').serialize(),
  305. dataType: 'json'
  306. }).done(function(res) {
  307. if (!res.ok) {
  308. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  309. $('#delete-errors').addClass('alert-danger');
  310. } else {
  311. var page = res.page;
  312. top.location.href = page.path + '?unlinked=true';
  313. }
  314. });
  315. return false;
  316. });
  317. $('#create-portal-button').on('click', function(e) {
  318. $('.portal').removeClass('hide');
  319. $('.content-main').addClass('on-edit');
  320. $('.portal a[data-toggle="tab"][href="#edit-form"]').tab('show');
  321. var path = $('.content-main').data('path');
  322. if (path != '/' && $('.content-main').data('page-id') == '') {
  323. var upperPage = path.substr(0, path.length - 1);
  324. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  325. if (res.ok && res.page) {
  326. $('#portal-warning-modal').modal('show');
  327. }
  328. });
  329. }
  330. });
  331. $('#portal-form-close').on('click', function(e) {
  332. $('.portal').addClass('hide');
  333. $('.content-main').removeClass('on-edit');
  334. return false;
  335. });
  336. /*
  337. * wrap short path with <strong></strong>
  338. */
  339. $('.page-list-link').each(function() {
  340. var $link = $(this);
  341. var text = $link.text();
  342. var path = $link.data('path');
  343. var shortPath = String($link.data('short-path')); // convert to string
  344. if (path == null || shortPath == null) {
  345. // continue
  346. return;
  347. }
  348. path = entities.encodeHTML(path);
  349. var pattern = escapeStringRegexp(entities.encodeHTML(shortPath)) + '(/)?$';
  350. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  351. });
  352. // for list page
  353. $('a[data-toggle="tab"][href="#view-timeline"]').on('show.bs.tab', function() {
  354. var isShown = $('#view-timeline').data('shown');
  355. if (isShown == 0) {
  356. $('#view-timeline .timeline-body').each(function()
  357. {
  358. var id = $(this).attr('id');
  359. var contentId = '#' + id + ' > script';
  360. var revisionBody = '#' + id + ' .revision-body';
  361. var $revisionBody = $(revisionBody);
  362. var revisionPath = '#' + id + ' .revision-path';
  363. var markdown = entities.decodeHTML($(contentId).html());
  364. var parsedHTML = crowiRenderer.render(markdown, $revisionBody.get(0));
  365. $revisionBody.html(parsedHTML);
  366. $('.template-create-button', revisionBody).on('click', function() {
  367. var path = $(this).data('path');
  368. var templateId = $(this).data('template');
  369. var template = $('#' + templateId).html();
  370. crowi.saveDraft(path, template);
  371. top.location.href = path;
  372. });
  373. });
  374. $('#view-timeline').data('shown', 1);
  375. }
  376. });
  377. // login
  378. $('#register').on('click', function() {
  379. $('#login-dialog').addClass('to-flip');
  380. return false;
  381. });
  382. $('#login').on('click', function() {
  383. $('#login-dialog').removeClass('to-flip');
  384. return false;
  385. });
  386. $('#register-form input[name="registerForm[username]"]').change(function(e) {
  387. var username = $(this).val();
  388. $('#input-group-username').removeClass('has-error');
  389. $('#help-block-username').html("");
  390. $.getJSON('/_api/check_username', {username: username}, function(json) {
  391. if (!json.valid) {
  392. $('#help-block-username').html('<i class="fa fa-warning"></i> This User ID is not available.<br>');
  393. $('#input-group-username').addClass('has-error');
  394. }
  395. });
  396. });
  397. if (pageId) {
  398. // if page exists
  399. var $rawTextOriginal = $('#raw-text-original');
  400. if ($rawTextOriginal.length > 0) {
  401. var markdown = entities.decodeHTML($('#raw-text-original').html());
  402. var dom = $('#revision-body-content').get(0);
  403. // create context object
  404. var context = {
  405. markdown,
  406. dom,
  407. currentPagePath: decodeURIComponent(location.pathname)
  408. };
  409. crowi.interceptorManager.process('preRender', context)
  410. .then(() => crowi.interceptorManager.process('prePreProcess', context))
  411. .then(() => {
  412. context.markdown = crowiRenderer.preProcess(context.markdown);
  413. })
  414. .then(() => crowi.interceptorManager.process('postPreProcess', context))
  415. .then(() => {
  416. var revisionBody = $('#revision-body-content');
  417. var parsedHTML = crowiRenderer.render(context.markdown, context.dom);
  418. context.parsedHTML = parsedHTML;
  419. Promise.resolve(context);
  420. })
  421. .then(() => crowi.interceptorManager.process('postRender', context))
  422. .then(() => crowi.interceptorManager.process('preRenderHtml', context))
  423. // render HTML with jQuery
  424. .then(() => {
  425. $('#revision-body-content').html(context.parsedHTML);
  426. $('.template-create-button').on('click', function() {
  427. var path = $(this).data('path');
  428. var templateId = $(this).data('template');
  429. var template = $('#' + templateId).html();
  430. crowi.saveDraft(path, template);
  431. top.location.href = path;
  432. });
  433. Crowi.appendEditSectionButtons('#revision-body-content', markdown);
  434. Promise.resolve($('#revision-body-content'));
  435. })
  436. // process interceptors for post rendering
  437. .then((bodyElement) => {
  438. context = Object.assign(context, {bodyElement})
  439. return crowi.interceptorManager.process('postRenderHtml', context);
  440. });
  441. }
  442. // header
  443. var $header = $('#page-header');
  444. if ($header.length > 0) {
  445. var headerHeight = $header.outerHeight(true);
  446. $('.header-wrap').css({height: (headerHeight + 16) + 'px'});
  447. $header.affix({
  448. offset: {
  449. top: function() {
  450. return headerHeight + 86; // (54 header + 16 header padding-top + 16 content padding-top)
  451. }
  452. }
  453. });
  454. $('[data-affix-disable]').on('click', function(e) {
  455. var $elm = $($(this).data('affix-disable'));
  456. $(window).off('.affix');
  457. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  458. return false;
  459. });
  460. }
  461. /*
  462. * transplanted to React components -- 2017.06.02 Yuki Takei
  463. *
  464. // omg
  465. function createCommentHTML(revision, creator, comment, commentedAt) {
  466. var $comment = $('<div>');
  467. var $commentImage = $('<img class="picture picture-rounded">')
  468. .attr('src', Crowi.userPicture(creator));
  469. var $commentCreator = $('<div class="page-comment-creator">')
  470. .text(creator.username);
  471. var $commentRevision = $('<a class="page-comment-revision label">')
  472. .attr('href', '?revision=' + revision)
  473. .text(revision.substr(0,8));
  474. if (revision !== revisionId) {
  475. $commentRevision.addClass('label-default');
  476. } else {
  477. $commentRevision.addClass('label-primary');
  478. }
  479. var $commentMeta = $('<div class="page-comment-meta">')
  480. //日付変換
  481. .text(moment(commentedAt).format('YYYY/MM/DD HH:mm:ss') + ' ')
  482. .append($commentRevision);
  483. var $commentBody = $('<div class="page-comment-body">')
  484. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  485. var $commentMain = $('<div class="page-comment-main">')
  486. .append($commentCreator)
  487. .append($commentBody)
  488. .append($commentMeta)
  489. $comment.addClass('page-comment');
  490. if (creator._id === currentUser) {
  491. $comment.addClass('page-comment-me');
  492. }
  493. if (revision !== revisionId) {
  494. $comment.addClass('page-comment-old');
  495. }
  496. $comment
  497. .append($commentImage)
  498. .append($commentMain);
  499. return $comment;
  500. }
  501. // get comments
  502. var $pageCommentList = $('.page-comments-list');
  503. var $pageCommentListNewer = $('#page-comments-list-newer');
  504. var $pageCommentListCurrent = $('#page-comments-list-current');
  505. var $pageCommentListOlder = $('#page-comments-list-older');
  506. var hasNewer = false;
  507. var hasOlder = false;
  508. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  509. if (res.ok) {
  510. var comments = res.comments;
  511. $.each(comments, function(i, comment) {
  512. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  513. if (comment.revision == revisionId) {
  514. $pageCommentListCurrent.append(commentContent);
  515. } else {
  516. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  517. $pageCommentListNewer.append(commentContent);
  518. hasNewer = true;
  519. } else {
  520. $pageCommentListOlder.append(commentContent);
  521. hasOlder = true;
  522. }
  523. }
  524. });
  525. }
  526. }).fail(function(data) {
  527. }).always(function() {
  528. if (!hasNewer) {
  529. $('.page-comments-list-toggle-newer').hide();
  530. }
  531. if (!hasOlder) {
  532. $pageCommentListOlder.addClass('collapse');
  533. $('.page-comments-list-toggle-older').hide();
  534. }
  535. });
  536. // post comment event
  537. $('#page-comment-form').on('submit', function() {
  538. var $button = $('#comment-form-button');
  539. $button.attr('disabled', 'disabled');
  540. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  541. $button.prop('disabled', false);
  542. if (data.ok) {
  543. var comment = data.comment;
  544. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  545. $('#comment-form-comment').val('');
  546. $('#comment-form-message').text('');
  547. } else {
  548. $('#comment-form-message').text(data.error);
  549. }
  550. }).fail(function(data) {
  551. if (data.status !== 200) {
  552. $('#comment-form-message').text(data.statusText);
  553. }
  554. });
  555. return false;
  556. });
  557. */
  558. // Like
  559. var $likeButton = $('.like-button');
  560. var $likeCount = $('#like-count');
  561. $likeButton.click(function() {
  562. var liked = $likeButton.data('liked');
  563. var token = $likeButton.data('csrftoken');
  564. if (!liked) {
  565. $.post('/_api/likes.add', {_csrf: token, page_id: pageId}, function(res) {
  566. if (res.ok) {
  567. MarkLiked();
  568. }
  569. });
  570. } else {
  571. $.post('/_api/likes.remove', {_csrf: token, page_id: pageId}, function(res) {
  572. if (res.ok) {
  573. MarkUnLiked();
  574. }
  575. });
  576. }
  577. return false;
  578. });
  579. var $likerList = $("#liker-list");
  580. var likers = $likerList.data('likers');
  581. if (likers && likers.length > 0) {
  582. var users = crowi.findUserByIds(likers.split(','));
  583. if (users) {
  584. AddToLikers(users);
  585. }
  586. }
  587. function AddToLikers (users) {
  588. $.each(users, function(i, user) {
  589. $likerList.append(CreateUserLinkWithPicture(user));
  590. });
  591. }
  592. function MarkLiked()
  593. {
  594. $likeButton.addClass('active');
  595. $likeButton.data('liked', 1);
  596. $likeCount.text(parseInt($likeCount.text()) + 1);
  597. }
  598. function MarkUnLiked()
  599. {
  600. $likeButton.removeClass('active');
  601. $likeButton.data('liked', 0);
  602. $likeCount.text(parseInt($likeCount.text()) - 1);
  603. }
  604. if (!isSeen) {
  605. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  606. // ignore unless response has error
  607. if (res.ok && res.seenUser) {
  608. $('#content-main').data('page-is-seen', 1);
  609. }
  610. });
  611. }
  612. function CreateUserLinkWithPicture (user) {
  613. var $userHtml = $('<a>');
  614. $userHtml.data('user-id', user._id);
  615. $userHtml.attr('href', '/user/' + user.username);
  616. $userHtml.attr('title', user.name);
  617. var $userPicture = $('<img class="picture picture-xs picture-rounded">');
  618. $userPicture.attr('alt', user.name);
  619. $userPicture.attr('src', Crowi.userPicture(user));
  620. $userHtml.append($userPicture);
  621. return $userHtml;
  622. }
  623. // presentation
  624. var presentaionInitialized = false
  625. , $b = $('body');
  626. $(document).on('click', '.toggle-presentation', function(e) {
  627. var $a = $(this);
  628. e.preventDefault();
  629. $b.toggleClass('overlay-on');
  630. if (!presentaionInitialized) {
  631. presentaionInitialized = true;
  632. $('<iframe />').attr({
  633. src: $a.attr('href')
  634. }).appendTo($('#presentation-container'));
  635. }
  636. }).on('click', '.fullscreen-layer', function() {
  637. $b.toggleClass('overlay-on');
  638. });
  639. //
  640. var me = $('body').data('me');
  641. var socket = io();
  642. socket.on('page edited', function (data) {
  643. if (data.user._id != me
  644. && data.page.path == pagePath) {
  645. $('#notifPageEdited').show();
  646. $('#notifPageEdited .edited-user').html(data.user.name);
  647. }
  648. });
  649. } // end if pageId
  650. // hash handling
  651. if (isSavedStatesOfTabChanges) {
  652. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  653. window.location.hash = '#revision-history';
  654. window.history.replaceState('', 'History', '#revision-history');
  655. });
  656. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  657. window.location.hash = '#edit-form';
  658. window.history.replaceState('', 'Edit', '#edit-form');
  659. });
  660. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  661. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  662. window.location.hash = '#';
  663. window.history.replaceState('', '', location.href);
  664. });
  665. }
  666. else {
  667. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  668. window.history.replaceState('', 'History', '#revision-history');
  669. });
  670. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  671. window.history.replaceState('', 'Edit', '#edit-form');
  672. });
  673. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  674. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  675. });
  676. // replace all href="#edit-form" link behaviors
  677. $(document).on('click', 'a[href="#edit-form"]', function() {
  678. window.location.replace('#edit-form');
  679. });
  680. }
  681. // focus to editor when 'shown.bs.tab' event fired
  682. $('a[href="#edit-form"]').on('shown.bs.tab', function(e) {
  683. Crowi.setCaretLineAndFocusToEditor();
  684. });
  685. });
  686. Crowi.getRevisionBodyContent = function() {
  687. return $('#revision-body-content').html();
  688. }
  689. Crowi.replaceRevisionBodyContent = function(html) {
  690. $('#revision-body-content').html(html);
  691. }
  692. Crowi.findHashFromUrl = function(url)
  693. {
  694. var match;
  695. if (match = url.match(/#(.+)$/)) {
  696. return `#${match[1]}`;
  697. }
  698. return "";
  699. }
  700. Crowi.findSectionHeader = function(hash) {
  701. if (hash.length == 0) {
  702. return;
  703. }
  704. // omit '#'
  705. const id = hash.replace('#', '');
  706. // don't use jQuery and document.querySelector
  707. // because hash may containe Base64 encoded strings
  708. const elem = document.getElementById(id);
  709. if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
  710. return elem;
  711. }
  712. return null;
  713. }
  714. Crowi.unhighlightSelectedSection = function(hash)
  715. {
  716. const elem = Crowi.findSectionHeader(hash);
  717. if (elem != null) {
  718. elem.classList.remove('highlighted');
  719. }
  720. }
  721. Crowi.highlightSelectedSection = function(hash)
  722. {
  723. const elem = Crowi.findSectionHeader(hash);
  724. if (elem != null) {
  725. elem.classList.add('highlighted');
  726. }
  727. }
  728. window.addEventListener('load', function(e) {
  729. // hash on page
  730. if (location.hash) {
  731. if (location.hash == '#edit-form') {
  732. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  733. // focus
  734. Crowi.setCaretLineAndFocusToEditor();
  735. }
  736. if (location.hash == '#revision-history') {
  737. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  738. }
  739. }
  740. if (crowi && crowi.users || crowi.users.length == 0) {
  741. var totalUsers = crowi.users.length;
  742. var $listLiker = $('.page-list-liker');
  743. $listLiker.each(function(i, liker) {
  744. var count = $(liker).data('count') || 0;
  745. if (count/totalUsers > 0.05) {
  746. $(liker).addClass('popular-page-high');
  747. // 5%
  748. } else if (count/totalUsers > 0.02) {
  749. $(liker).addClass('popular-page-mid');
  750. // 2%
  751. } else if (count/totalUsers > 0.005) {
  752. $(liker).addClass('popular-page-low');
  753. // 0.5%
  754. }
  755. });
  756. var $listSeer = $('.page-list-seer');
  757. $listSeer.each(function(i, seer) {
  758. var count = $(seer).data('count') || 0;
  759. if (count/totalUsers > 0.10) {
  760. // 10%
  761. $(seer).addClass('popular-page-high');
  762. } else if (count/totalUsers > 0.05) {
  763. // 5%
  764. $(seer).addClass('popular-page-mid');
  765. } else if (count/totalUsers > 0.02) {
  766. // 2%
  767. $(seer).addClass('popular-page-low');
  768. }
  769. });
  770. }
  771. Crowi.highlightSelectedSection(location.hash);
  772. Crowi.modifyScrollTop();
  773. Crowi.setCaretLineAndFocusToEditor();
  774. });
  775. window.addEventListener('hashchange', function(e) {
  776. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  777. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  778. Crowi.modifyScrollTop();
  779. // hash on page
  780. if (location.hash) {
  781. if (location.hash == '#edit-form') {
  782. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  783. }
  784. if (location.hash == '#revision-history') {
  785. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  786. }
  787. }
  788. else {
  789. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  790. }
  791. });
  792. window.addEventListener('keydown', (event) => {
  793. const target = event.target;
  794. // ignore when target dom is input
  795. const inputPattern = /^input|textinput|textarea$/i;
  796. if (target.tagName.match(inputPattern)) {
  797. return;
  798. }
  799. switch (event.key) {
  800. case 'e':
  801. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  802. Crowi.handleKeyEHandler(event);
  803. }
  804. break;
  805. case 'c':
  806. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  807. Crowi.handleKeyCHandler(event);
  808. }
  809. break;
  810. case '/':
  811. if (event.ctrlKey || event.metaKey) {
  812. Crowi.handleKeyCtrlSlashHandler(event);
  813. }
  814. break;
  815. }
  816. });