crowi.js 24 KB

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