crowi.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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. const data = $(this).serialize() + `&socketClientId=${crowi.getSocketClientId()}`;
  323. $.ajax({
  324. type: 'POST',
  325. url: '/_api/pages.rename',
  326. data: data,
  327. dataType: 'json'
  328. })
  329. .done(function(res) {
  330. if (!res.ok) {
  331. // if already exists
  332. $('#renamePage .msg-already-exists, #unportalize .msg-already-exists').show();
  333. $('#renamePage #linkToNewPage, #unportalize #linkToNewPage').html(`
  334. <a href="${nameValueMap.new_path}">${nameValueMap.new_path} <i class="icon-login"></i></a>
  335. `);
  336. }
  337. else {
  338. const page = res.page;
  339. top.location.href = page.path + '?renamed=' + pagePath;
  340. }
  341. });
  342. return false;
  343. });
  344. // duplicate
  345. $('#duplicatePage').on('shown.bs.modal', function(e) {
  346. $('#duplicatePage #duplicatePageName').focus();
  347. $('#duplicatePage .msg-already-exists').hide();
  348. });
  349. $('#duplicatePageForm, #unportalize-form').submit(function(e) {
  350. // create name-value map
  351. let nameValueMap = {};
  352. $(this).serializeArray().forEach((obj) => {
  353. nameValueMap[obj.name] = obj.value;
  354. });
  355. $.ajax({
  356. type: 'POST',
  357. url: '/_api/pages.duplicate',
  358. data: $(this).serialize(),
  359. dataType: 'json'
  360. }).done(function(res) {
  361. if (!res.ok) {
  362. // if already exists
  363. $('#duplicatePage .msg-already-exists').show();
  364. $('#duplicatePage #linkToNewPage').html(`
  365. <a href="${nameValueMap.new_path}">${nameValueMap.new_path} <i class="icon-login"></i></a>
  366. `);
  367. }
  368. else {
  369. const page = res.page;
  370. top.location.href = page.path + '?duplicated=' + pagePath;
  371. }
  372. });
  373. return false;
  374. });
  375. // delete
  376. $('#delete-page-form').submit(function(e) {
  377. $.ajax({
  378. type: 'POST',
  379. url: '/_api/pages.remove',
  380. data: $('#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. $('#revert-delete-page-form').submit(function(e) {
  395. $.ajax({
  396. type: 'POST',
  397. url: '/_api/pages.revertRemove',
  398. data: $('#revert-delete-page-form').serialize(),
  399. dataType: 'json'
  400. }).done(function(res) {
  401. if (!res.ok) {
  402. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  403. $('#delete-errors').addClass('alert-danger');
  404. }
  405. else {
  406. const page = res.page;
  407. top.location.href = page.path;
  408. }
  409. });
  410. return false;
  411. });
  412. $('#unlink-page-form').submit(function(e) {
  413. $.ajax({
  414. type: 'POST',
  415. url: '/_api/pages.unlink',
  416. data: $('#unlink-page-form').serialize(),
  417. dataType: 'json'
  418. })
  419. .done(function(res) {
  420. if (!res.ok) {
  421. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  422. $('#delete-errors').addClass('alert-danger');
  423. }
  424. else {
  425. const page = res.page;
  426. top.location.href = page.path + '?unlinked=true';
  427. }
  428. });
  429. return false;
  430. });
  431. $('#create-portal-button').on('click', function(e) {
  432. $('body').addClass('on-edit');
  433. const path = $('.content-main').data('path');
  434. if (path != '/' && $('.content-main').data('page-id') == '') {
  435. const upperPage = path.substr(0, path.length - 1);
  436. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  437. if (res.ok && res.page) {
  438. $('#portal-warning-modal').modal('show');
  439. }
  440. });
  441. }
  442. });
  443. $('#portal-form-close').on('click', function(e) {
  444. $('body').removeClass('on-edit');
  445. return false;
  446. });
  447. /*
  448. * wrap short path with <strong></strong>
  449. */
  450. $('#view-list .page-list-ul-flat .page-list-link').each(function() {
  451. const $link = $(this);
  452. /* eslint-disable no-unused-vars */
  453. const text = $link.text();
  454. /* eslint-enable */
  455. let path = decodeURIComponent($link.data('path'));
  456. const shortPath = decodeURIComponent($link.data('short-path')); // convert to string
  457. if (path == null || shortPath == null) {
  458. // continue
  459. return;
  460. }
  461. path = entities.encodeHTML(path);
  462. const pattern = escapeStringRegexp(entities.encodeHTML(shortPath)) + '(/)?$';
  463. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  464. });
  465. // for list page
  466. let growiRendererForTimeline = null;
  467. $('a[data-toggle="tab"][href="#view-timeline"]').on('show.bs.tab', function() {
  468. const isShown = $('#view-timeline').data('shown');
  469. if (growiRendererForTimeline == null) {
  470. growiRendererForTimeline = new GrowiRenderer(crowi, crowiRenderer, {mode: 'timeline'});
  471. }
  472. if (isShown == 0) {
  473. $('#view-timeline .timeline-body').each(function() {
  474. const id = $(this).attr('id');
  475. const contentId = '#' + id + ' > script';
  476. const revisionBody = '#' + id + ' .revision-body';
  477. const revisionBodyElem = document.querySelector(revisionBody);
  478. /* eslint-disable no-unused-vars */
  479. const revisionPath = '#' + id + ' .revision-path';
  480. /* eslint-enable */
  481. const pagePath = document.getElementById(id).getAttribute('data-page-path');
  482. const markdown = entities.decodeHTML($(contentId).html());
  483. ReactDOM.render(<Page crowi={crowi} crowiRenderer={growiRendererForTimeline} markdown={markdown} pagePath={pagePath} />, revisionBodyElem);
  484. });
  485. $('#view-timeline').data('shown', 1);
  486. }
  487. });
  488. if (pageId) {
  489. // for Crowi Template LangProcessor
  490. $('.template-create-button', $('#revision-body')).on('click', function() {
  491. const path = $(this).data('path');
  492. const templateId = $(this).data('template');
  493. const template = $('#' + templateId).html();
  494. crowi.saveDraft(path, template);
  495. top.location.href = `${path}#edit`;
  496. });
  497. // Like
  498. const $likeButton = $('.like-button');
  499. const $likeCount = $('#like-count');
  500. $likeButton.click(function() {
  501. const liked = $likeButton.data('liked');
  502. const token = $likeButton.data('csrftoken');
  503. if (!liked) {
  504. $.post('/_api/likes.add', {_csrf: token, page_id: pageId}, function(res) {
  505. if (res.ok) {
  506. MarkLiked();
  507. }
  508. });
  509. }
  510. else {
  511. $.post('/_api/likes.remove', {_csrf: token, page_id: pageId}, function(res) {
  512. if (res.ok) {
  513. MarkUnLiked();
  514. }
  515. });
  516. }
  517. return false;
  518. });
  519. const $likerList = $('#liker-list');
  520. const likers = $likerList.data('likers');
  521. if (likers && likers.length > 0) {
  522. const users = crowi.findUserByIds(likers.split(','));
  523. if (users) {
  524. AddToLikers(users);
  525. }
  526. }
  527. /* eslint-disable no-inner-declarations */
  528. function AddToLikers(users) {
  529. $.each(users, function(i, user) {
  530. $likerList.append(CreateUserLinkWithPicture(user));
  531. });
  532. }
  533. function MarkLiked() {
  534. $likeButton.addClass('active');
  535. $likeButton.data('liked', 1);
  536. $likeCount.text(parseInt($likeCount.text()) + 1);
  537. }
  538. function MarkUnLiked() {
  539. $likeButton.removeClass('active');
  540. $likeButton.data('liked', 0);
  541. $likeCount.text(parseInt($likeCount.text()) - 1);
  542. }
  543. function CreateUserLinkWithPicture(user) {
  544. const $userHtml = $('<a>');
  545. $userHtml.data('user-id', user._id);
  546. $userHtml.attr('href', '/user/' + user.username);
  547. $userHtml.attr('title', user.name);
  548. const $userPicture = $('<img class="picture picture-xs img-circle">');
  549. $userPicture.attr('alt', user.name);
  550. $userPicture.attr('src', Crowi.userPicture(user));
  551. $userHtml.append($userPicture);
  552. return $userHtml;
  553. }
  554. /* eslint-enable */
  555. if (!isSeen) {
  556. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  557. // ignore unless response has error
  558. if (res.ok && res.seenUser) {
  559. $('#content-main').data('page-is-seen', 1);
  560. }
  561. });
  562. }
  563. // presentation
  564. let presentaionInitialized = false
  565. , $b = $('body');
  566. $(document).on('click', '.toggle-presentation', function(e) {
  567. const $a = $(this);
  568. e.preventDefault();
  569. $b.toggleClass('overlay-on');
  570. if (!presentaionInitialized) {
  571. presentaionInitialized = true;
  572. $('<iframe />').attr({
  573. src: $a.attr('href')
  574. }).appendTo($('#presentation-container'));
  575. }
  576. }).on('click', '.fullscreen-layer', function() {
  577. $b.toggleClass('overlay-on');
  578. });
  579. } // end if pageId
  580. // tab changing handling
  581. $('a[href="#edit"]').on('show.bs.tab', function() {
  582. $('body').addClass('on-edit');
  583. $('body').addClass('builtin-editor');
  584. });
  585. $('a[href="#edit"]').on('hide.bs.tab', function() {
  586. $('body').removeClass('on-edit');
  587. $('body').removeClass('builtin-editor');
  588. });
  589. $('a[href="#hackmd"]').on('show.bs.tab', function() {
  590. $('body').addClass('on-edit');
  591. $('body').addClass('hackmd');
  592. });
  593. $('a[href="#hackmd"]').on('hide.bs.tab', function() {
  594. $('body').removeClass('on-edit');
  595. $('body').removeClass('hackmd');
  596. });
  597. // hash handling
  598. if (isSavedStatesOfTabChanges) {
  599. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  600. window.location.hash = '#revision-history';
  601. window.history.replaceState('', 'History', '#revision-history');
  602. });
  603. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', function() {
  604. window.location.hash = '#edit';
  605. window.history.replaceState('', 'Edit', '#edit');
  606. });
  607. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', function() {
  608. window.location.hash = '#hackmd';
  609. window.history.replaceState('', 'HackMD', '#hackmd');
  610. });
  611. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  612. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  613. window.location.hash = '#';
  614. window.history.replaceState('', '', location.href);
  615. });
  616. }
  617. else {
  618. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  619. window.history.replaceState('', 'History', '#revision-history');
  620. });
  621. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', function() {
  622. window.history.replaceState('', 'Edit', '#edit');
  623. });
  624. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', function() {
  625. window.history.replaceState('', 'HackMD', '#hackmd');
  626. });
  627. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  628. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  629. });
  630. // replace all href="#edit" link behaviors
  631. $(document).on('click', 'a[href="#edit"]', function() {
  632. window.location.replace('#edit');
  633. });
  634. }
  635. // focus to editor when 'shown.bs.tab' event fired
  636. $('a[href="#edit"]').on('shown.bs.tab', function(e) {
  637. Crowi.setCaretLineAndFocusToEditor();
  638. });
  639. });
  640. window.addEventListener('load', function(e) {
  641. // hash on page
  642. if (location.hash) {
  643. if (location.hash === '#edit' || location.hash === '#edit-form') {
  644. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  645. // focus
  646. Crowi.setCaretLineAndFocusToEditor();
  647. }
  648. else if (location.hash == '#hackmd') {
  649. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  650. }
  651. else if (location.hash == '#revision-history') {
  652. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  653. }
  654. }
  655. if (crowi && crowi.users || crowi.users.length == 0) {
  656. const totalUsers = crowi.users.length;
  657. const $listLiker = $('.page-list-liker');
  658. $listLiker.each(function(i, liker) {
  659. const count = $(liker).data('count') || 0;
  660. if (count/totalUsers > 0.05) {
  661. $(liker).addClass('popular-page-high');
  662. // 5%
  663. }
  664. else if (count/totalUsers > 0.02) {
  665. $(liker).addClass('popular-page-mid');
  666. // 2%
  667. }
  668. else if (count/totalUsers > 0.005) {
  669. $(liker).addClass('popular-page-low');
  670. // 0.5%
  671. }
  672. });
  673. const $listSeer = $('.page-list-seer');
  674. $listSeer.each(function(i, seer) {
  675. const count = $(seer).data('count') || 0;
  676. if (count/totalUsers > 0.10) {
  677. // 10%
  678. $(seer).addClass('popular-page-high');
  679. }
  680. else if (count/totalUsers > 0.05) {
  681. // 5%
  682. $(seer).addClass('popular-page-mid');
  683. }
  684. else if (count/totalUsers > 0.02) {
  685. // 2%
  686. $(seer).addClass('popular-page-low');
  687. }
  688. });
  689. }
  690. Crowi.highlightSelectedSection(location.hash);
  691. Crowi.modifyScrollTop();
  692. Crowi.initSlimScrollForRevisionToc();
  693. Crowi.initAffix();
  694. });
  695. window.addEventListener('hashchange', function(e) {
  696. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  697. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  698. Crowi.modifyScrollTop();
  699. // hash on page
  700. if (location.hash) {
  701. if (location.hash === '#edit') {
  702. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  703. }
  704. else if (location.hash == '#hackmd') {
  705. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  706. }
  707. else if (location.hash == '#revision-history') {
  708. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  709. }
  710. }
  711. else {
  712. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  713. }
  714. });
  715. window.addEventListener('keydown', (event) => {
  716. const target = event.target;
  717. // ignore when target dom is input
  718. const inputPattern = /^input|textinput|textarea$/i;
  719. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  720. return;
  721. }
  722. switch (event.key) {
  723. case 'e':
  724. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  725. Crowi.handleKeyEHandler(event);
  726. }
  727. break;
  728. case 'c':
  729. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  730. Crowi.handleKeyCHandler(event);
  731. }
  732. break;
  733. case '/':
  734. if (event.ctrlKey || event.metaKey) {
  735. Crowi.handleKeyCtrlSlashHandler(event);
  736. }
  737. break;
  738. }
  739. });