crowi.js 24 KB

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