crowi.js 28 KB

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