crowi.js 24 KB

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