crowi.js 25 KB

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